Sha256: 59b48094ab29e05426b99a0172b1397adb2c3505019d560c852e13051d676c3e

Contents?: true

Size: 1018 Bytes

Versions: 3

Compression:

Stored size: 1018 Bytes

Contents

module Standby
  class Base
    def initialize(target)
      @target = decide_with(target)
    end

    def run(&block)
      run_on @target, &block
    end

  private

    def decide_with(target)
      if Standby.disabled || target == :primary
        :primary
      elsif inside_transaction?
        raise Standby::Error.new('on_standby cannot be used inside transaction block!')
      elsif target == :null_state
        :standby
      elsif target.present?
        "standby_#{target}".to_sym
      else
        raise Standby::Error.new('on_standby cannot be used with a nil target!')
      end
    end

    def inside_transaction?
      open_transactions = run_on(:primary) { ActiveRecord::Base.connection.open_transactions }
      open_transactions > Standby::Transaction.base_depth
    end

    def run_on(target)
      backup = Thread.current[:_standby] # Save for recursive nested calls
      Thread.current[:_standby] = target
      yield
    ensure
      Thread.current[:_standby] = backup
    end
  end
end

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
standby-5.0.0 lib/standby/base.rb
slavery-4.0.0 lib/standby/base.rb
standby-4.0.0 lib/standby/base.rb