lock_method

It’s like alias_method, but it’s lock_method!

Example

require 'lock_method'
class Blog
  attr_accessor :url

  def get_latest_entries
    sleep 5
  end
  lock_method :get_latest_entries

  # used by lock_method to differentiate between instances
  def hash
    url.hash
  end
end

Then you can do

my_blog.get_latest_entries => it will start...
my_blog.get_latest_entries => this will raise LockMethod::Locked if you try to run it before the other call finishes

Just in case, you can clear them

my_blog.clear_method_lock :get_latest_entries

Real-world usage

In production use at carbon.brighterplanet.com, the Brighter Planet emission estimate web service.

Ignores arguments when locking a method

lock_method ignores arguments when locking. So if you call Foo.bar(:a), calls to Foo.bar(:b) will be locked until the first call finishes.

Maybe future versions will support this.

Defining #hash

If you want to lock instance methods, you should define #hash on those instances.

You should follow Ruby convention and have #hash return a Fixnum.

Ideally, you should try to make a String or a Hash and call the standard #hash on that.

Note: this is NOT the same thing as #to_hash! That returns a Hash… but what we want is an integer “hash code.”

Defining #method_lock_hash instead of #hash

If you don’t want to modify #hash, you can use #method_lock_hash instead.

Configuration (and supported cache clients)

The default is to use filesystem lockfiles, usually in /tmp/lock_method/*.

If you want to share locks among various machines, you can use a Memcached or Redis client:

LockMethod.config.storage = Memcached.new '127.0.0.1:11211'

or

LockMethod.config.storage = Redis.new

or this might even work…

LockMethod.config.storage = Rails.cache

See Config for the full list of supported caches.

Copyright 2011 Seamus Abshere