Skip to content
This repository


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Like alias_method, but it's lock_method! (lockfiles)

branch: master

Fetching latest commit…


Cannot retrieve the latest commit at this time

Octocat-spinner-32 lib
Octocat-spinner-32 test
Octocat-spinner-32 .gitignore
Octocat-spinner-32 CHANGELOG
Octocat-spinner-32 Gemfile
Octocat-spinner-32 README.rdoc
Octocat-spinner-32 Rakefile
Octocat-spinner-32 lock_method.gemspec


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

Lets you lock a method so that only one process can call it at a time. Defaults to using lockfiles on the local file system, but can be configured to store the locks in Memcached or Redis, allowing the method locks to hold over multiple hosts.

Real-world usage

In production use at and


require 'lock_method'
class Blog
  attr_accessor :url

  def get_latest_entries
    sleep 5
  lock_method :get_latest_entries

  # used by lock_method to differentiate between instances
  def as_lock

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.lock_method_clear :get_latest_entries

Pays attention to method arguments

If you lock*args), calling will not lock out

Defining #as_lock

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

Locking across hosts

If you want to lock across hosts, just use shared storage, like a remote Redis or memcached instance.

If you want to lock locally, but you're using shared storage, just get the hostname of the locking instance into the as_lock.

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: = ''

or =

or this might even work… = Rails.cache

See Config for the full list of supported caches.


Copyright 2011 Seamus Abshere

Something went wrong with that request. Please try again.