Add ActiveRecord::Base#with_lock #4531

Merged
merged 1 commit into from Jan 19, 2012

Projects

None yet

2 participants

@exviva

Add a with_lock method to ActiveRecord objects, which starts
a transaction, locks the object (pessimistically) and yields to the block.
The method takes one (optional) parameter and passes it to lock!.

Before:

class Order < ActiveRecord::Base
  def cancel!
    transaction do
      lock!
      # ... cancelling logic
    end
  end
end

After:

class Order < ActiveRecord::Base
  def cancel!
    with_lock do
      # ... cancelling logic
    end
  end
end

This PR is a modification of #4503. @tenderlove, please merge and backport to 3-2-stable :).

@exviva exviva Add ActiveRecord::Base#with_lock
Add a `with_lock` method to ActiveRecord objects, which starts
a transaction, locks the object (pessimistically) and yields to the block.
The method takes one (optional) parameter and passes it to `lock!`.

Before:

    class Order < ActiveRecord::Base
      def cancel!
        transaction do
          lock!
          # ... cancelling logic
        end
      end
    end

After:

    class Order < ActiveRecord::Base
      def cancel!
        with_lock do
          # ... cancelling logic
        end
      end
    end
7afbc89
@tenderlove tenderlove merged commit 0056a75 into rails:master Jan 19, 2012
@exviva exviva deleted the exviva:pessimistic_with_lock branch Mar 10, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment