Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a tenant change hook #333

Merged
merged 2 commits into from
Jan 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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