Sha256: 5c4b6290e6b2084889e1ff7b9a2190f8e3186e76237042129423a2ae7434c7ea

Contents?: true

Size: 1.17 KB

Versions: 8

Compression:

Stored size: 1.17 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)

        if defined?(::PG)
          @catch_exceptions << ::PG::Error
          @catch_exceptions << ::PGError if defined?(::PGError)
        end

        @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

8 entries across 8 versions & 1 rubygems

Version Path
fresh_connection-2.4.4 lib/fresh_connection/access_control.rb
fresh_connection-2.4.3 lib/fresh_connection/access_control.rb
fresh_connection-2.4.2 lib/fresh_connection/access_control.rb
fresh_connection-2.4.1 lib/fresh_connection/access_control.rb
fresh_connection-2.4.0 lib/fresh_connection/access_control.rb
fresh_connection-2.4.0.rc4 lib/fresh_connection/access_control.rb
fresh_connection-2.4.0.rc3 lib/fresh_connection/access_control.rb
fresh_connection-2.4.0.rc1 lib/fresh_connection/access_control.rb