Class: Gorynich::Switcher

Inherits:
Object
  • Object
show all
Defined in:
lib/gorynich/switcher.rb

Instance Method Summary collapse

Constructor Details

#initialize(config:) ⇒ Switcher

Returns a new instance of Switcher.



3
4
5
# File 'lib/gorynich/switcher.rb', line 3

def initialize(config:)
  @config = config
end

Instance Method Details

#analyze(env) ⇒ [String, Hash]

Hander for rack middleware’s variables

Parameters:

  • env (Hash)

    middleware’s variables

Returns:

  • ([String, Hash])

    tenant, options



14
15
16
17
18
19
20
21
# File 'lib/gorynich/switcher.rb', line 14

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



35
36
37
38
39
# File 'lib/gorynich/switcher.rb', line 35

def with(tenant, **opts, &block)
  with_database(tenant) do
    with_current(tenant, **opts, &block)
  end
end

#with_current(tenant, **opts, &block) ⇒ Object



29
30
31
32
33
# File 'lib/gorynich/switcher.rb', line 29

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



23
24
25
26
27
# File 'lib/gorynich/switcher.rb', line 23

def with_database(tenant)
  ::ActiveRecord::Base.connected_to role: tenant.to_sym do
    yield(tenant)
  end
end

#with_each_tenant(except: [], &block) ⇒ Object



41
42
43
44
45
46
# File 'lib/gorynich/switcher.rb', line 41

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