Skip to content

Commit

Permalink
import patch from rails-on-services#182
Browse files Browse the repository at this point in the history
  • Loading branch information
shot056 committed May 27, 2024
1 parent 8578ccf commit 2389bc1
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 20 deletions.
41 changes: 21 additions & 20 deletions lib/apartment/tenant.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,36 +19,37 @@ module Tenant
# @return {subclass of Apartment::AbstractAdapter}
#
def adapter
Thread.current[:apartment_adapter] ||= begin
adapter_method = "#{config[:adapter]}_adapter"

if defined?(JRUBY_VERSION)
case config[:adapter]
when /mysql/
adapter_method = 'jdbc_mysql_adapter'
when /postgresql/
adapter_method = 'jdbc_postgresql_adapter'
end
end
current_adapter = Thread.current.thread_variable_get(:apartment_adapter)
return current_adapter if current_adapter

begin
require "apartment/adapters/#{adapter_method}"
rescue LoadError
raise "The adapter `#{adapter_method}` is not yet supported"
end
adapter_method = "#{config[:adapter]}_adapter"

unless respond_to?(adapter_method)
raise AdapterNotFound, "database configuration specifies nonexistent #{config[:adapter]} adapter"
if defined?(JRUBY_VERSION)
case config[:adapter]
when /mysql/
adapter_method = 'jdbc_mysql_adapter'
when /postgresql/
adapter_method = 'jdbc_postgresql_adapter'
end
end

send(adapter_method, config)
begin
require "apartment/adapters/#{adapter_method}"
rescue LoadError
raise "The adapter `#{adapter_method}` is not yet supported"
end

unless respond_to?(adapter_method)
raise AdapterNotFound, "database configuration specifies nonexistent #{config[:adapter]} adapter"
end

Thread.current.thread_variable_set(:apartment_adapter, send(adapter_method, config))
end

# Reset config and adapter so they are regenerated
#
def reload!(config = nil)
Thread.current[:apartment_adapter] = nil
Thread.current.thread_variable_set(:apartment_adapter, nil)
@config = config
end

Expand Down
8 changes: 8 additions & 0 deletions spec/tenant_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,14 @@
thread.join
expect(subject.current).to eq(db1)
end

it 'maintains the current tenant across fibers within a thread' do
subject.switch!(db1)
expect(subject.current).to eq(db1)
fiber = Fiber.new { expect(subject.current).to eq(db1) }
fiber.resume
expect(subject.current).to eq(db1)
end
end
end

Expand Down

0 comments on commit 2389bc1

Please sign in to comment.