开发者

Rails 3 question - locking row for specific time

I'm building a rails 3 app in which it sells a limited number of items. I'm looking for a way to hold an item for a specific amount of time so that when someone selects an item, they have time to purchase it before someone else can purchase it before them. I have done some research as to row locking but haven't found a usable method thus far开发者_运维知识库 for specifying a time.

Thanks for any help or ideas


This is a typical workflow pattern, where you acquire an object for a duration. You can achieve this easily by implementing application level locks.

1) Add lock fields to the model.

locker_id
lock_until

2) Now you can implement this logic in the Product model.

class Product

  belongs_to :locker, :class_name => "User",
           :condition => lambda { {:conditions => ["lock_until < ? ", Time.now]}}

  def locked?
    !lock_until.nil? and lock_until > Time.now
  end

  def lock_for_duration(usr, duration=10.minutes)
    return false if locked?
    self.locker_id = user.id
    self.lock_until = duration.from_now
    self.save   
  end

  def release_lock
    return true unless locked?
    self.locker_id = nil
    self.lock_until = nil
    self.save    
  end
end

Here is how to use this:

usr = User.first
product.lock_for_duration(usr, 30.minutes)
product.locked?
product.locker?


I would recommend setting a locked_until timestamp that's checked whenever someone attempts to buy one of these items. If there are no items with a locked_until time in the past, then all items are "sold out". For actual selling of the items, I would have a sold boolean field.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜