Sha256: 692abc6cb4a2a829388dc1dd1eab6e2aa2d53658411889aa8f94bc45ea738437

Contents?: true

Size: 1.38 KB

Versions: 12

Compression:

Stored size: 1.38 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 db.setnx(key(:_lock), lock_timeout)
        next unless lock = db.get(key(:_lock))
        sleep(wait) and next unless lock_expired?(lock)

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

    # Release the lock.
    # @see Model#mutex
    def unlock!
      db.del(key(:_lock))
    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

12 entries across 12 versions & 1 rubygems

Version Path
ohm-contrib-0.0.28 lib/ohm/contrib/locking.rb
ohm-contrib-0.0.27 lib/ohm/contrib/locking.rb
ohm-contrib-0.0.26 lib/ohm/contrib/locking.rb
ohm-contrib-0.0.25 lib/ohm/contrib/locking.rb
ohm-contrib-0.0.24 lib/ohm/contrib/locking.rb
ohm-contrib-0.0.23 lib/ohm/contrib/locking.rb
ohm-contrib-0.0.22 lib/ohm/contrib/locking.rb
ohm-contrib-0.0.21 lib/ohm/contrib/locking.rb
ohm-contrib-0.0.20 lib/ohm/contrib/locking.rb
ohm-contrib-0.0.19 lib/ohm/contrib/locking.rb
ohm-contrib-0.0.18 lib/ohm/contrib/locking.rb
ohm-contrib-0.0.17 lib/ohm/contrib/locking.rb