Module: CurlyMustache::Locking::ClassMethods
- Defined in:
- lib/curly_mustache/locking.rb
Instance Method Summary collapse
- #do_locked_block(id, record, &block) ⇒ Object
- #lock(id, timeout = nil) ⇒ Object
- #lock_and_find(id, timeout = nil, &block) ⇒ Object
- #lock_key(id) ⇒ Object
- #lock_prefix ⇒ Object
- #lock_with_timeout(id, timeout) ⇒ Object
- #unlock(id) ⇒ Object
Instance Method Details
#do_locked_block(id, record, &block) ⇒ Object
44 45 46 47 48 49 50 |
# File 'lib/curly_mustache/locking.rb', line 44 def do_locked_block(id, record, &block) yield(record) rescue Exception raise ensure unlock(id) end |
#lock(id, timeout = nil) ⇒ Object
13 14 15 16 17 18 19 |
# File 'lib/curly_mustache/locking.rb', line 13 def lock(id, timeout = nil) if timeout.nil? connection.lock(lock_key(id)) else lock_with_timeout(id, timeout) end end |
#lock_and_find(id, timeout = nil, &block) ⇒ Object
34 35 36 37 38 39 40 41 42 |
# File 'lib/curly_mustache/locking.rb', line 34 def lock_and_find(id, timeout = nil, &block) lock(id, timeout) or return false unlock(id) and return if (record = find(id)).blank? if block_given? do_locked_block(id, record, &block) else record end end |
#lock_key(id) ⇒ Object
52 53 54 |
# File 'lib/curly_mustache/locking.rb', line 52 def lock_key(id) "#{lock_prefix}:#{id_to_key(id)}" end |
#lock_prefix ⇒ Object
56 57 58 |
# File 'lib/curly_mustache/locking.rb', line 56 def lock_prefix "lock" end |
#lock_with_timeout(id, timeout) ⇒ Object
21 22 23 24 25 26 27 28 |
# File 'lib/curly_mustache/locking.rb', line 21 def lock_with_timeout(id, timeout) start_time = Time.now while (Time.now.to_f - start_time.to_f) < timeout connection.lock(lock_key(id)) and return true sleep(0.1) end raise Timeout::Error, "aquiring lock for #{id_to_key(id)}" end |
#unlock(id) ⇒ Object
30 31 32 |
# File 'lib/curly_mustache/locking.rb', line 30 def unlock(id) connection.unlock(lock_key(id)) end |