Class: Gorynich::Switcher

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

Constant Summary collapse

DATABASE_RETRY_LIMIT =
2

Instance Method Summary collapse

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

Parameters:

  • env (Hash)

    middleware’s variables

Returns:

  • ([String, Hash])

    tenant, options



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

Parameters:

  • tenant (String, Symbol)

    Tenant (database role)



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