Sha256: bf0cd99c7f4eb7ece487c6df0908cff28fd0107781c92d57c8de15345bd23b22

Contents?: true

Size: 1.36 KB

Versions: 17

Compression:

Stored size: 1.36 KB

Contents

module Ohm
  # This module is a straight extraction from Ohm. The only difference is
  # that this allows for a custom sleep value.
  #
  # In addition, since future ohm versions might drop mutexes, I thought it
  # might be a good idea to preseve this feature as a drop-in module.
  module Locking
    # Lock the object before executing the block, and release it once the block
    # is done.
    #
    # @example
    #
    #   post = Order.create(:customer => Customer.create)
    #   post.mutex(0.01) do
    #     # this block is in a mutex!
    #   end
    def mutex(wait = 0.1)
      lock!(wait)
      yield
      self
    ensure
      unlock!
    end

  protected
    # Lock the object so no other instances can modify it.
    # This method implements the design pattern for locks
    # described at: http://code.google.com/p/redis/wiki/SetnxCommand
    #
    # @see Model#mutex
    def lock!(wait = 0.1)
      until key[:_lock].setnx(lock_timeout)
        next unless lock = key[:_lock].get
        sleep(wait) and next unless lock_expired?(lock)

        break unless lock = key[:_lock].getset(lock_timeout)
        break if lock_expired?(lock)
      end
    end

    # Release the lock.
    # @see Model#mutex
    def unlock!
      key[:_lock].del
    end

    def lock_timeout
      Time.now.to_f + 1
    end

    def lock_expired? lock
      lock.to_f < Time.now.to_f
    end
  end
end

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
ohm-contrib-2.0.0.alpha5 lib/ohm/locking.rb
ohm-contrib-2.0.0.alpha4 lib/ohm/locking.rb
ohm-contrib-2.0.0.alpha3 lib/ohm/locking.rb
ohm-contrib-2.0.0.alpha2 lib/ohm/locking.rb
ohm-contrib-1.2 lib/ohm/locking.rb
ohm-contrib-1.1.0 lib/ohm/locking.rb
ohm-contrib-1.0.1 lib/ohm/locking.rb
ohm-contrib-1.0.0 lib/ohm/locking.rb
ohm-contrib-1.0.0.rc5 lib/ohm/locking.rb
ohm-contrib-1.0.0.rc4 lib/ohm/locking.rb
ohm-contrib-1.0.0.rc3 lib/ohm/locking.rb
ohm-contrib-1.0.0.rc2 lib/ohm/locking.rb
ohm-contrib-1.0.rc1 lib/ohm/locking.rb
ohm-contrib-1.0.rc0 lib/ohm/locking.rb
ohm-contrib-0.0.31 lib/ohm/contrib/locking.rb
ohm-contrib-0.0.30 lib/ohm/contrib/locking.rb
ohm-contrib-0.0.29 lib/ohm/contrib/locking.rb