class TN::AdvisoryLock

Public Class Methods

new(key, wait: false) click to toggle source
# 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
string_to_int(string) click to toggle source

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

# 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) { || ... } click to toggle source
# 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

Public Instance Methods

exclusive() { || ... } click to toggle source
# File lib/tn/advisory_lock.rb, line 23
def exclusive
  if acquired?
    begin
      yield
    ensure
      release!
    end
  else
    return false
  end
  true
end

Private Instance Methods

acquired?() click to toggle source
# File lib/tn/advisory_lock.rb, line 38
def acquired?
  TN.execute_sql("select #{sql_function}(#{@key})") != "f"
end
release!() click to toggle source
# File lib/tn/advisory_lock.rb, line 50
def release!
  TN.execute_sql("select pg_advisory_unlock(#{@key})")
end
sql_function() click to toggle source
# File lib/tn/advisory_lock.rb, line 42
def sql_function
  if @wait
    "pg_advisory_lock"
  else
    "pg_try_advisory_lock"
  end
end