diff --git a/lib/acts_as_tenant.rb b/lib/acts_as_tenant.rb index 20bd25b..f407401 100644 --- a/lib/acts_as_tenant.rb +++ b/lib/acts_as_tenant.rb @@ -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 diff --git a/lib/acts_as_tenant/configuration.rb b/lib/acts_as_tenant/configuration.rb index e75ebcf..c18685c 100644 --- a/lib/acts_as_tenant/configuration.rb +++ b/lib/acts_as_tenant/configuration.rb @@ -1,6 +1,7 @@ module ActsAsTenant class Configuration attr_writer :require_tenant, :pkey + attr_reader :tenant_change_hook def require_tenant @require_tenant ||= false @@ -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 diff --git a/spec/acts_as_tenant/configuration_spec.rb b/spec/acts_as_tenant/configuration_spec.rb index 9d1f33a..c12edd4 100644 --- a/spec/acts_as_tenant/configuration_spec.rb +++ b/spec/acts_as_tenant/configuration_spec.rb @@ -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