influitive / apartment

Database multi-tenancy for Rack (and Rails) applications
2.67k stars 463 forks source link

Question: Is there a way to hook on the tenant switching mechanism? #562

Closed michalvalasek closed 5 years ago

michalvalasek commented 6 years ago

I'd like to set the Current.tenant automatically on every Apartment::Tenant.switch! call. Is there a way how to do this? Any hook I can use from outside?

mikecmpbll commented 5 years ago

yep—https://github.com/influitive/apartment/pull/307

michalvalasek commented 5 years ago

@mikecmpbll Thanks, I've seen that PR but I haven't found any doc on how to actually use it. What am I missing?

mikecmpbll commented 5 years ago

it uses Active Support Callbacks. afaicr you can define callbacks as such:

Apartment.set_callback :switch, :after do
  puts "switched"
end
michalvalasek commented 5 years ago

Thank you very much! I’ll create a PR where I add it to the readme - if that’s ok.

jean-francois-labbe commented 5 years ago

With rails 5.2.1 and ruby 2.6.0

When using

Apartment.set_callback :switch, :after do
  puts "switched"
end

I got

initializers/apartment.rb:116:in `<main>': undefined method `set_callback' for Apartment:Module (NoMethodError)

when using

Apartment::Tenant.set_callback :switch, :after do
  puts "switched"
end

I got

initializers/apartment.rb:116: warning: Apartment::Tenant#set_callback at ruby-2.6.0/lib/ruby/2.6.0/forwardable.rb:158 forwarding to private method Apartment::Adapters::PostgresqlSchemaAdapter#set_callback
ruby-2.6.0/lib/ruby/2.6.0/forwardable.rb:228:in `set_callback': undefined method `set_callback' for #<Apartment::Adapters::PostgresqlSchemaAdapter:0x000055f7c6e37e70> (NoMethodError)

I just found set_callback mentioned in this issue and this file: https://github.com/influitive/apartment/blob/a4332c3222210b11f5e8c27fa4c1a18b492e9629/lib/apartment/tenant.rb

As anyone faced this issue?

noma4i commented 5 years ago

@jean-francois-labbe dirty workaround:

require 'apartment/adapters/abstract_adapter'
Apartment::Adapters::AbstractAdapter.set_callback :switch, :after do
  puts 'switched'
end