Class: Cerberus::Latch

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

Class Method Summary collapse

Class Method Details

.lock(lock_file, options = {}) ⇒ Object

Emulate File.flock



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/cerberus/latch.rb', line 6

def self.lock(lock_file, options = {})
  if File.exists?(lock_file)
    modif_time = File::Stat.new(lock_file).mtime
    ttl = options[:lock_ttl]

    if ttl and modif_time + ttl < Time.now
      File.delete(lock_file)
    else
      return
    end
  end

  begin
    FileUtils.mkpath(File.dirname(lock_file))
    File.new(lock_file, 'w').close
    yield
  ensure
    File.delete(lock_file)
  end
end