Skip to content

Commit

Permalink
Add a tenant change hook (#333)
Browse files Browse the repository at this point in the history
* add a tenant change hook

* cleanup syntax for standardrb

---------

Co-authored-by: Christopher Winslett <[email protected]>
  • Loading branch information
Winslett and Christopher Winslett authored Jan 11, 2024
1 parent 8e8f9de commit 599d8af
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/acts_as_tenant.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@ module ActsAsTenant

class Current < ActiveSupport::CurrentAttributes
attribute :current_tenant, :acts_as_tenant_unscoped

def current_tenant=(tenant)
super.tap do
configuration.tenant_change_hook.call(tenant) if configuration.tenant_change_hook.present?
end
end

def configuration
Module.nesting.last.class_variable_get(:@@configuration)
end
end

class << self
Expand Down
6 changes: 6 additions & 0 deletions lib/acts_as_tenant/configuration.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
module ActsAsTenant
class Configuration
attr_writer :require_tenant, :pkey
attr_reader :tenant_change_hook

def require_tenant
@require_tenant ||= false
Expand All @@ -27,5 +28,10 @@ def job_scope=(scope)
scope
end
end

def tenant_change_hook=(hook)
raise(ArgumentError, "tenant_change_hook must be a Proc") unless hook.is_a?(Proc)
@tenant_change_hook = hook
end
end
end
28 changes: 28 additions & 0 deletions spec/acts_as_tenant/configuration_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,33 @@

expect(ActsAsTenant.should_require_tenant?).to eq(false)
end

it "runs a hook on current_tenant" do
truthy = false
ActsAsTenant.configure do |config|
config.tenant_change_hook = lambda do |tenant|
truthy = true
end
end

ActsAsTenant.current_tenant = "foobar"

expect(truthy).to eq(true)
end

it "runs a hook on with_tenant" do
truthy = false
ActsAsTenant.configure do |config|
config.tenant_change_hook = lambda do |tenant|
truthy = true
end
end

ActsAsTenant.with_tenant("foobar") do
# do nothing
end

expect(truthy).to eq(true)
end
end
end

0 comments on commit 599d8af

Please sign in to comment.