Class: Lockfile

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

Constant Summary collapse

LockDenied =
Class.new(StandardError)
MissingParent =
Class.new(StandardError)
NoPermission =
Class.new(StandardError)
StaleLock =
Class.new(StandardError)

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Lockfile

Returns a new instance of Lockfile.



7
8
9
10
11
12
# File 'lib/lockfile.rb', line 7

def initialize(path)
  @file_path = path
  @lock_path = path.sub_ext(".lock")

  @lock = nil
end

Instance Method Details

#commitObject



32
33
34
35
36
37
38
# File 'lib/lockfile.rb', line 32

def commit
  raise_on_stale_lock

  @lock.close
  File.rename(@lock_path, @file_path)
  @lock = nil
end

#hold_for_updateObject



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/lockfile.rb', line 14

def hold_for_update
  unless @lock
    flags = File::RDWR | File::CREAT | File::EXCL
    @lock = File.open(@lock_path, flags)
  end
rescue Errno::EEXIST
  raise LockDenied, "Unable to create '#{ @lock_path }': File exists."
rescue Errno::ENOENT => error
  raise MissingParent, error.message
rescue Errno::EACCES => error
  raise NoPermission, error.message
end

#rollbackObject



40
41
42
43
44
45
46
# File 'lib/lockfile.rb', line 40

def rollback
  raise_on_stale_lock

  @lock.close
  File.unlink(@lock_path)
  @lock = nil
end

#write(string) ⇒ Object



27
28
29
30
# File 'lib/lockfile.rb', line 27

def write(string)
  raise_on_stale_lock
  @lock.write(string)
end