Sha256: 289a35b7a2b8aec0ed14be76252129cf6d5e9b363fc26ed47d04a1e87b65ff3f

Contents?: true

Size: 1.39 KB

Versions: 2

Compression:

Stored size: 1.39 KB

Contents

require 'fresh_connection/connection_specification'

module EbisuConnection
  class Replica
    attr_reader :hostname, :weight

    def initialize(conf, spec_name)
      case conf
      when String
        host, weight = conf.split(/\s*,\s*/)
        @hostname, @port = host.split(/\s*:\s*/)
      when Hash
        @hostname = conf["host"] || conf[:host]
        weight = conf["weight"] || conf[:weight]
        @port = conf["port"] || conf[:port]
      else
        raise ArgumentError, "replica config is invalid"
      end

      spec = FreshConnection::ConnectionSpecification.new(
        spec_name, modify_spec: modify_spec
      ).spec

      @pool = ActiveRecord::ConnectionAdapters::ConnectionPool.new(spec)
      @weight = (weight || 1).to_i
    end

    def connection
      @pool.connection
    end
    
    def put_aside!
      return unless active_connection?
      return if connection.transaction_open?

      release_connection
    end

    def active_connection?
      @pool.active_connection?
    end

    def release_connection
      @pool.release_connection
    end

    def disconnect!
      @pool.disconnect!
    end

    private

    def modify_spec
      modify_spec = {"host" => @hostname}
      return modify_spec if !defined?(@port) || @port.nil?
      return modify_spec if @port.respond_to?(:empty?) && @port.empty?

      modify_spec["port"] = @port.to_i
      modify_spec
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
ebisu_connection-3.1.0 lib/ebisu_connection/replica.rb
ebisu_connection-3.0.0 lib/ebisu_connection/replica.rb