Sha256: 3e1a901094085c9c1cdb97cd987573e14e61205c7caee1138bd8c4baf37da3eb

Contents?: true

Size: 1.23 KB

Versions: 10

Compression:

Stored size: 1.23 KB

Contents

module Gorynich
  class Switcher
    def initialize(config:)
      @config = config
    end

    #
    # Hander for rack middleware's variables
    #
    # @param [Hash] env middleware's variables
    #
    # @return [[String, Hash]] tenant, options
    #
    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

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

    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

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

    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
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
gorynich-1.2.1.184916 lib/gorynich/switcher.rb
gorynich-1.2.0.180668 lib/gorynich/switcher.rb
gorynich-1.1.1.148381 lib/gorynich/switcher.rb
gorynich-1.1.0.142168 lib/gorynich/switcher.rb
gorynich-1.1.0.142154 lib/gorynich/switcher.rb
gorynich-1.1.0.142147 lib/gorynich/switcher.rb
gorynich-1.1.0.142142 lib/gorynich/switcher.rb
gorynich-1.1.0.142139 lib/gorynich/switcher.rb
gorynich-1.1.0.142136 lib/gorynich/switcher.rb
gorynich-1.1.0.142046 lib/gorynich/switcher.rb