Sha256: e37e937b91e982d483739fe588976d957726ade087ccd372e18f8e866ac4c143

Contents?: true

Size: 1.88 KB

Versions: 8

Compression:

Stored size: 1.88 KB

Contents

module ActiveReplicas
  class ProxyingConnection
    def initialize(connection:, is_primary:, proxy:)
      @connection = connection
      @is_primary = is_primary
      @proxy      = proxy
    end

    # Forwards a call to its own connection or back up to the proxy pool's
    # primary connection.
    #
    # role   - Either `:primary` or `:replica`: indicates which database role
    #          is necessary to execute this command.
    # method - Symbol of method to send to a connection.
    def delegate_to(role, method, *args, &block)
      if @is_primary
        @connection.send method, *args, &block
      else
        if role == :primary
          # Need to get a primary connection from the proxy pool.
          @proxy.primary_connection.send method, *args, &block
        else
          @connection.send method, *args, &block
        end
      end
    end

    # Helper method to easily use the primary pool from any model:
    #
    #   MyModel.connection.with_primary { ... }
    def with_primary
      @proxy.with_primary { yield }
    end

    # Returns the underlying proxied database connection.
    def proxied_connection
      @connection
    end

    class << self
      # Partially cribbed from:
      #    https://github.com/kickstarter/replica_pools/blob/master/lib/replica_pools/connection_proxy.rb#L20
      def generate_replica_delegations
        Railtie.replica_delegated_methods.each do |method|
          generate_delegation method, :replica
        end
      end

      def generate_primary_delegations
        Railtie.primary_delegated_methods.each do |method|
          generate_delegation method, :primary
        end
      end

      def generate_delegation(method_name, role)
        class_eval <<-END, __FILE__, __LINE__ + 1
          def #{method_name}(*args, &block)
            delegate_to(:#{role}, :#{method_name}, *args, &block)
          end
        END
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
active_replicas-0.1.7 lib/active_replicas/proxying_connection.rb
active_replicas-0.1.6 lib/active_replicas/proxying_connection.rb
active_replicas-0.1.5 lib/active_replicas/proxying_connection.rb
active_replicas-0.1.4 lib/active_replicas/proxying_connection.rb
active_replicas-0.1.3 lib/active_replicas/proxying_connection.rb
active_replicas-0.1.2 lib/active_replicas/proxying_connection.rb
active_replicas-0.1.1 lib/active_replicas/proxying_connection.rb
active_replicas-0.1.0 lib/active_replicas/proxying_connection.rb