Class: DBLock::Lock

Inherits:
Object
  • Object
show all
Defined in:
lib/db_lock.rb

Class Method Summary collapse

Class Method Details

.get(name, timeout = 0) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/db_lock.rb', line 6

def get(name, timeout=0)
  timeout = timeout.to_i # catches nil
  timeout = 0 if timeout < 0
  raise "invalid lock name: #{name.inspect}" if !name or name.to_s.length == 0
  raise AlreadyLocked.new("Already lock in progress") if locked?
  name = prefixed_lock_name(name)
  res = ActiveRecord::Base.connection.execute("SELECT GET_LOCK('#{name}', #{timeout})")
  if @locked = (res and res.first and res.first[0] == 1)
    yield
  else
    raise AlreadyLocked.new("Unable to obtain lock '#{name}' within #{timeout} seconds") unless @locked
  end
ensure
  ActiveRecord::Base.connection.execute("SELECT RELEASE_LOCK('#{name}')") if @locked
  @locked = false
end

.locked?Boolean

Returns:

  • (Boolean)


23
24
25
# File 'lib/db_lock.rb', line 23

def locked?
  @locked ||= false
end