Sha256: 3ffc59228b9164e63ea566ac913b866e86ba00e24f7a229f9952aabe729e743a

Contents?: true

Size: 1.09 KB

Versions: 3

Compression:

Stored size: 1.09 KB

Contents

module FreshConnection
  class AccessControl
    class << self
      def force_master_access(&block)
        switch_to(:master, &block)
      end

      def access(enable_replica_access, &block)
        if access_db
          block.call
        else
          db = enable_replica_access ? :replica : :master
          switch_to(db, &block)
        end
      end

      def replica_access?
        access_db == :replica
      end

      def catch_exceptions
        return @catch_exceptions if defined?(@catch_exceptions)
        @catch_exceptions = [ActiveRecord::StatementInvalid]
        @catch_exceptions << ::Mysql2::Error if defined?(::Mysql2)
        @catch_exceptions += [::PG::Error, ::PGError] if defined?(::PG)
        @catch_exceptions
      end

      private

      def switch_to(new_db)
        old_db = access_db
        access_to(new_db)
        yield
      ensure
        access_to(old_db)
      end

      def access_db
        Thread.current[:fresh_connection_access_target]
      end

      def access_to(db)
        Thread.current[:fresh_connection_access_target] = db
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
fresh_connection-2.3.2 lib/fresh_connection/access_control.rb
fresh_connection-2.3.1 lib/fresh_connection/access_control.rb
fresh_connection-2.3.0 lib/fresh_connection/access_control.rb