Sha256: 600e04ec358f6f2464ccd480a12db3915355f9da9e2b53539903918bbd1bce35

Contents?: true

Size: 1.3 KB

Versions: 8

Compression:

Stored size: 1.3 KB

Contents

module DbCharmer
  module MultiDbProxy
    class OnDbProxy < BlankSlate
      def initialize(model_class, slave)
        @model = model_class
        @slave = slave
      end

    private

      def method_missing(meth, *args, &block)
        @model.on_db(@slave) do |m|
          m.__send__(meth, *args, &block)
        end
      end
    end

    module ClassMethods
      def on_db(con, proxy_target = nil)
        proxy_target ||= self
        
        # Chain call
        return OnDbProxy.new(proxy_target, con) unless block_given?

        # Block call
        begin
          self.db_charmer_connection_level += 1
          old_proxy = db_charmer_connection_proxy
          switch_connection_to(con, DbCharmer.migration_connections_should_exist?)
          yield(proxy_target)
        ensure
          switch_connection_to(old_proxy)
          self.db_charmer_connection_level -= 1
        end
      end
    end
    
    module MasterSlaveClassMethods
      def on_slave(con = nil, proxy_target = nil, &block)
        con ||= db_charmer_random_slave
        raise ArgumentError, "No slaves found in the class and no slave connection given" unless con
        on_db(con, proxy_target, &block)
      end

      def on_master(proxy_target = nil, &block)
        on_db(nil, proxy_target, &block)
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 3 rubygems

Version Path
glebpom-db-charmer-1.1.5 lib/db_charmer/multi_db_proxy.rb
glebpom-db-charmer-1.3.0 lib/db_charmer/multi_db_proxy.rb
kovyrin-db-charmer-1.1.0 lib/db_charmer/multi_db_proxy.rb
kovyrin-db-charmer-1.1.2 lib/db_charmer/multi_db_proxy.rb
kovyrin-db-charmer-1.1.3 lib/db_charmer/multi_db_proxy.rb
kovyrin-db-charmer-1.2.0 lib/db_charmer/multi_db_proxy.rb
db-charmer-1.3.1 lib/db_charmer/multi_db_proxy.rb
glebpom-db-charmer-1.4.0 lib/db_charmer/multi_db_proxy.rb