Module: ExpirableLocking

Defined in:
lib/expirable_locking.rb

Defined Under Namespace

Modules: InstanceMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object



3
4
5
6
7
8
# File 'lib/expirable_locking.rb', line 3

def self.extended(base)
  base.named_scope :unlocked, lambda {
    { :conditions => [ "locked_at IS NULL OR locked_at < ?", base.lock_duration.ago ] }
  }
  base.send(:include, InstanceMethods)
end

Instance Method Details

#lock(record) ⇒ Object



26
27
28
# File 'lib/expirable_locking.rb', line 26

def lock(record)
  1 == unlocked.touch_lock(record)
end

#lock_durationObject



22
23
24
# File 'lib/expirable_locking.rb', line 22

def lock_duration
  10.minutes
end

#touch_lock(record) ⇒ Object

Updates lock timestamp without triggering validations/callbacks.



37
38
39
40
41
42
43
44
45
46
# File 'lib/expirable_locking.rb', line 37

def touch_lock(record)
  locked_at = default_timezone == :utc ? Time.now.utc : Time.now
  result    = update_all({ :locked_at => locked_at }, { :id => record })

  if result == 1
    record.write_attribute_without_dirty(:locked_at, locked_at)
  end

  result
end

#unlock(record) ⇒ Object



30
31
32
33
34
# File 'lib/expirable_locking.rb', line 30

def unlock(record)
  return true if record.destroyed?

  1 == update_all({ :locked_at => nil }, { :id => record, :locked_at => record.locked_at })
end