Reputation: 7275
I'd like to be able to "reserve" an element similar to how an airplane seat is locked for a short period of time before it's actually paid for. I think the best way is to do it through the database and preferably at the ORM layer.
Here's an example:
ActiveRecord::Base.transaction do
bar = Bar.find(1, :lock => true)
# do my stuff
end
I need a more flexible solution though.
Here's how I am imagining it to work conceptually:
# action1:
# put an expiring lock (30s) on an element (don't block unrelated code)
# other code
# action2 (after payment):
# come back to the locked element to claim ownership of it
UPDATE: Anyone trying to do this in Rails should try using built-in optimistic locking functionality first.
Upvotes: 0
Views: 136
Reputation: 7275
I could have a separate table specifically for this purpose called potential_owner
. It would have a timestamp, so that one can figure out the timing. Basically it would work something like that:
# lock the table
# check latest record to see if the element is available
# add a new record or die
This is pretty simple to implement, however locking is not fine-grained. The table describes potential ownership of different elements, and a simple check locks down the whole table. In Tass's solution only the row for a particular element is locked.
Upvotes: 0
Reputation: 21700
Add an additional column locked_until
- but beware of concurrency. I'd probably do that down on the db layer.
Upvotes: 2