Module: Barron::Tmpfile

Defined in:
lib/barron/tmpfile.rb

Class Method Summary collapse

Class Method Details

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



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

def lock name, options={}
  options = {
    :block => true,
    :tmpdir => '/tmp'
  }.merge(options)
  value = nil
  open("#{options[:tmpdir]}/barron-#{Digest::MD5.hexdigest("#{name}")}", File::RDWR|File::CREAT, 0666) do |f|
    begin
      if options[:block]
        f.flock(File::LOCK_EX)
        value = yield f
      elsif f.flock(File::LOCK_EX|File::LOCK_NB)
        value = yield f
      end
    ensure
      f.flock(File::LOCK_UN)
    end
  end
  value
end