Sha256: d640b42a777fc82e9c09999bc249b0432e6bf487611536b6b6529dc589416fc4

Contents?: true

Size: 799 Bytes

Versions: 1

Compression:

Stored size: 799 Bytes

Contents

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

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

  private

    def decide_with(target)
      raise Slavery::Error.new('on_slave cannot be used inside transaction block!') if inside_transaction?

      if Slavery.disabled
        :master
      else
        target
      end
    end

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

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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
slavery-2.1.0 lib/slavery/base.rb