Class: WithAdvisoryLock::Flock

Inherits:
Base
  • Object
show all
Defined in:
lib/with_advisory_lock/flock.rb

Instance Attribute Summary

Attributes inherited from Base

#connection, #lock_name, #shared, #timeout_seconds, #transaction

Instance Method Summary collapse

Methods inherited from Base

#already_locked?, #initialize, lock_stack, #lock_stack_item, #lock_str, #stable_hashcode, #unique_column_name, #with_advisory_lock_if_needed, #yield_with_lock, #yield_with_lock_and_timeout

Constructor Details

This class inherits a constructor from WithAdvisoryLock::Base

Instance Method Details

#file_ioObject



14
15
16
17
18
19
# File 'lib/with_advisory_lock/flock.rb', line 14

def file_io
  @file_io ||= begin
    FileUtils.touch(filename)
    File.open(filename, 'r+')
  end
end

#filenameObject



5
6
7
8
9
10
11
12
# File 'lib/with_advisory_lock/flock.rb', line 5

def filename
  @filename ||= begin
    safe = lock_str.to_s.gsub(/[^a-z0-9]/i, '')
    fn = ".lock-#{safe}-#{stable_hashcode(lock_str)}"
    # Let the user specify a directory besides CWD.
    ENV['FLOCK_DIR'] ? File.expand_path(fn, ENV['FLOCK_DIR']) : fn
  end
end

#release_lockObject



28
29
30
# File 'lib/with_advisory_lock/flock.rb', line 28

def release_lock
  0 == file_io.flock(File::LOCK_UN)
end

#try_lockObject



21
22
23
24
25
26
# File 'lib/with_advisory_lock/flock.rb', line 21

def try_lock
  if transaction
    raise ArgumentError, 'transaction level locks are not supported on SQLite'
  end
  0 == file_io.flock((shared ? File::LOCK_SH : File::LOCK_EX) | File::LOCK_NB)
end