From 599d8af0b4e52c0228806e901cb558901b2a356e Mon Sep 17 00:00:00 2001 From: Christopher Winslett Date: Wed, 10 Jan 2024 19:30:53 -0600 Subject: [PATCH] Add a tenant change hook (#333) * add a tenant change hook * cleanup syntax for standardrb --------- Co-authored-by: Christopher Winslett --- lib/acts_as_tenant.rb | 10 ++++++++ lib/acts_as_tenant/configuration.rb | 6 +++++ spec/acts_as_tenant/configuration_spec.rb | 28 +++++++++++++++++++++++ 3 files changed, 44 insertions(+) diff --git a/lib/acts_as_tenant.rb b/lib/acts_as_tenant.rb index 20bd25bb..f4074015 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 e75ebcfc..c18685c2 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 9d1f33ac..c12edd4e 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