Class: Ro::Lock

Inherits:
Object
  • Object
show all
Defined in:
lib/ro/lock.rb

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Lock

Returns a new instance of Lock.



3
4
5
6
# File 'lib/ro/lock.rb', line 3

def initialize(path)
  @path = path.to_s
  @fd = false
end

Instance Method Details

#lock(&block) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/ro/lock.rb', line 8

def lock(&block)
  open!

  if block
    begin
      lock!
      block.call
    ensure
      unlock!
    end
  else
    self
  end
end

#lock!Object



43
44
45
46
# File 'lib/ro/lock.rb', line 43

def lock!
  open!
  @fd.flock File::LOCK_EX
end

#open!Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/ro/lock.rb', line 23

def open!
  @fd ||= (
    fd =
      begin
        open(@path, 'ab+')
      rescue
        unless test(?e, @path)
          FileUtils.mkdir_p(@path)
          FileUtils.touch(@path)
        end

        open(@path, 'ab+')
      end

    fd.close_on_exec = true

    fd
  )
end

#unlock!Object



48
49
50
51
# File 'lib/ro/lock.rb', line 48

def unlock!
  open!
  @fd.flock File::LOCK_UN
end