Class: Gorynich::Switcher
- Inherits:
-
Object
- Object
- Gorynich::Switcher
- Defined in:
- lib/gorynich/switcher.rb
Constant Summary collapse
- DATABASE_RETRY_LIMIT =
2
Instance Method Summary collapse
-
#analyze(env) ⇒ [String, Hash]
Hander for rack middleware’s variables.
-
#initialize(config:) ⇒ Switcher
constructor
A new instance of Switcher.
- #with(tenant, **opts, &block) ⇒ Object
- #with_current(tenant, **opts, &block) ⇒ Object
-
#with_database(tenant) ⇒ Object
Connect to database.
- #with_each_tenant(except: [], &block) ⇒ Object
Constructor Details
#initialize(config:) ⇒ Switcher
Returns a new instance of Switcher.
5 6 7 |
# File 'lib/gorynich/switcher.rb', line 5 def initialize(config:) @config = config end |
Instance Method Details
#analyze(env) ⇒ [String, Hash]
Hander for rack middleware’s variables
16 17 18 19 20 21 22 23 |
# File 'lib/gorynich/switcher.rb', line 16 def analyze(env) return Gorynich.configuration.rack_env_handler.call(env) unless Gorynich.configuration.rack_env_handler.nil? host = env['SERVER_NAME'] tenant = Gorynich.instance.tenant_by_host(host) uri = Gorynich.instance.uri_by_host(host, tenant) [tenant, { host: host, uri: uri }] end |
#with(tenant, **opts, &block) ⇒ Object
59 60 61 62 63 |
# File 'lib/gorynich/switcher.rb', line 59 def with(tenant, **opts, &block) with_database(tenant) do with_current(tenant, **opts, &block) end end |
#with_current(tenant, **opts, &block) ⇒ Object
53 54 55 56 57 |
# File 'lib/gorynich/switcher.rb', line 53 def with_current(tenant, **opts, &block) Gorynich::Current.set(@config.config(tenant.to_s).merge(opts)) do block.call(Gorynich::Current.instance) if block.present? end end |
#with_database(tenant) ⇒ Object
Connect to database
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/gorynich/switcher.rb', line 30 def with_database(tenant) retries ||= 0 ::ActiveRecord::Base.connected_to role: tenant.to_sym do ::ActiveRecord::Base.connection_pool.with_connection do yield(tenant) end end rescue ::ActiveRecord::ConnectionNotEstablished => e config = ::Gorynich.instance config.actualize raise TenantNotFound, tenant unless config.tenants.include?(tenant.to_s) if (retries += 1) < DATABASE_RETRY_LIMIT ActiveRecord::Base.connection_handler.establish_connection( config.database(tenant), role: tenant.to_sym ) retry end raise e end |
#with_each_tenant(except: [], &block) ⇒ Object
65 66 67 68 69 70 |
# File 'lib/gorynich/switcher.rb', line 65 def with_each_tenant(except: [], &block) except = except.map(&:to_s) @config.tenants.reject { |v| except.include?(v) }.each do |tenant| with(tenant, &block) end end |