Sha256: fb71e75514fbd5a29f2dcaa8546b80df642fe5b62796aa26a2a694e57df61ea9

Contents?: true

Size: 1.08 KB

Versions: 9

Compression:

Stored size: 1.08 KB

Contents

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

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

      def slave_access?
        access_db == :slave
      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

9 entries across 9 versions & 1 rubygems

Version Path
fresh_connection-2.2.0 lib/fresh_connection/access_control.rb
fresh_connection-2.1.2 lib/fresh_connection/access_control.rb
fresh_connection-2.1.1 lib/fresh_connection/access_control.rb
fresh_connection-2.1.0 lib/fresh_connection/access_control.rb
fresh_connection-2.0.4 lib/fresh_connection/access_control.rb
fresh_connection-2.0.3 lib/fresh_connection/access_control.rb
fresh_connection-2.0.2 lib/fresh_connection/access_control.rb
fresh_connection-2.0.1 lib/fresh_connection/access_control.rb
fresh_connection-2.0.0 lib/fresh_connection/access_control.rb