Sha256: bff454529324140b971cf545735941f79dbf4595cb05a7d451c6e7a830eec61b

Contents?: true

Size: 1.38 KB

Versions: 4

Compression:

Stored size: 1.38 KB

Contents

module ActiveRecord::Turntable
  class Shard
    DEFAULT_CONFIG = {
      "connection" => (defined?(Rails) ? Rails.env : "development")
    }.with_indifferent_access

    def initialize(shard_spec)
      @config = DEFAULT_CONFIG.merge(shard_spec)
      @name = @config["connection"]
    end

    def connection_pool
      @connection_pool ||= retrieve_connection_pool
    end

    def connection
      connection = connection_pool.connection
      connection.turntable_shard_name = name
      connection
    end

    def name
      @name
    end

    private

    def retrieve_connection_pool
      ActiveRecord::Base.turntable_connections[name] ||=
        begin
          config = ActiveRecord::Base.configurations[Rails.env]["shards"][name]
          raise ArgumentError, "Unknown database config: #{name}, have #{ActiveRecord::Base.configurations.inspect}" unless config
          ActiveRecord::ConnectionAdapters::ConnectionPool.new(spec_for(config))
        end
    end

    def spec_for(config)
      begin
        require "active_record/connection_adapters/#{config['adapter']}_adapter"
      rescue LoadError => e
        raise "Please install the #{config['adapter']} adapter: `gem install activerecord-#{config['adapter']}-adapter` (#{e})"
      end
      adapter_method = "#{config['adapter']}_connection"
      ActiveRecord::Base::ConnectionSpecification.new(config, adapter_method)
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
activerecord-turntable-1.1.2 lib/active_record/turntable/shard.rb
activerecord-turntable-1.1.1 lib/active_record/turntable/shard.rb
activerecord-turntable-1.1.0 lib/active_record/turntable/shard.rb
activerecord-turntable-1.0.0 lib/active_record/turntable/shard.rb