Class: TN::AdvisoryLock

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, wait: false) ⇒ AdvisoryLock

Returns a new instance of AdvisoryLock.



4
5
6
7
8
# File 'lib/tn/advisory_lock.rb', line 4

def initialize(key, wait: false)
  key = self.class.string_to_int(key) unless key.is_a?(Integer)
  @key  = key
  @wait = wait
end

Class Method Details

.string_to_int(string) ⇒ Object

Convert a string to a int that’s needed for the advisory lock.



11
12
13
# File 'lib/tn/advisory_lock.rb', line 11

def self.string_to_int(string)
  Digest::SHA1.hexdigest(string)[0..10].to_i(36)
end

.with_lock(key, wait: false) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/tn/advisory_lock.rb', line 15

def self.with_lock(key, wait: false)
  result = nil
  new(key, wait: wait).exclusive do
    result = yield
  end
  result
end

Instance Method Details

#exclusiveObject



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/tn/advisory_lock.rb', line 23

def exclusive
  if acquired?
    begin
      yield
    ensure
      release!
    end
  else
    return false
  end
  true
end