Class: Lock

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/lock.rb

Class Method Summary collapse

Class Method Details

.get(name, args = {}) ⇒ Object

Get an atomic lock if value matches or is nil. Block until lock was successful if args was set to true



4
5
6
7
8
9
10
# File 'app/models/lock.rb', line 4

def self.get name, args = {}
  poll_time = args[:poll_time] || 10
  until (lock = get_lock_for(name, args)) || args[:blocking] != true do
    sleep poll_time
  end
  lock
end

.get_value(name) ⇒ Object

Return value of a lock. When no lock was found, nil will be returned.



48
49
50
51
52
53
54
55
# File 'app/models/lock.rb', line 48

def self.get_value name
  lock = self.where(:name => name).first
  if lock
    lock.value.nil? ? '' : lock.value
  else
    nil
  end
end

.release(names, args = {}) ⇒ Object

Release an atomic lock if value matches or is nil



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'app/models/lock.rb', line 14

def self.release names, args = {}
  successful = false

  if name
    # If names is a single string, transorm it to an array
    names = [names.to_s] if names.class == String || names.class == Symbol

    self.transaction do
      locks = self.where(:name => names).lock(true).all

      unless locks.blank?
        successful = true
        # Check, if the value of every selected lock matches the args[:value] unless no args[:value] was specified
        locks.each{ |l| successful = false unless (args[:value].nil? || (args[:value] != nil && args[:value] == l.value)) }
        # Now destroy the locks, if it is successful
        locks.each{ |l| l.destroy } if successful
      end
    end
  end

  successful
end

.release_allObject

Destroy all locks in one atomic operation



59
60
61
62
63
# File 'app/models/lock.rb', line 59

def self.release_all
  self.transaction do
    self.all.each { |l| l.destroy }
  end
end

.release_for_task(task) ⇒ Object

Release all locks for a given task. This is only working, if the value was set to “task #tasktask.id”



39
40
41
42
43
44
# File 'app/models/lock.rb', line 39

def self.release_for_task task
  self.transaction do
    locks = self.where(:value => "task #{task.id}").lock(true).all
    locks.each{ |l| l.destroy }
  end
end