Class: LockFile

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, logger = nil) ⇒ LockFile

Returns a new instance of LockFile.



8
9
10
11
12
13
14
# File 'lib/bin_script/lock_file.rb', line 8

def initialize(path, logger = nil)
  if path == nil
    raise "file path cannot be nil"
  end
  @path = path
  @logger = logger || $logger
end

Instance Attribute Details

#loggerObject

Returns the value of attribute logger.



3
4
5
# File 'lib/bin_script/lock_file.rb', line 3

def logger
  @logger
end

#pathObject

Returns the value of attribute path.



3
4
5
# File 'lib/bin_script/lock_file.rb', line 3

def path
  @path
end

#quietObject

Returns the value of attribute quiet.



3
4
5
# File 'lib/bin_script/lock_file.rb', line 3

def quiet
  @quiet
end

Instance Method Details

#lock(waiting_unlock = false) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/bin_script/lock_file.rb', line 16

def lock(waiting_unlock = false)
  flags = File::WRONLY | File::TRUNC | File::CREAT

  @f = File.open(@path, flags)
  flags = File::LOCK_EX
  flags |= File::LOCK_NB if waiting_unlock == false

  unless @f.flock flags
    log "File '#{@path}' already open in exclusive mode.\n"
    return true
  end
  return false
end

#log(str) ⇒ Object



37
38
39
40
41
42
43
44
# File 'lib/bin_script/lock_file.rb', line 37

def log(str)
  return if @quiet
  if @logger
    @logger.warn str
  else
    print str
  end
end

#unlockObject



30
31
32
33
34
35
# File 'lib/bin_script/lock_file.rb', line 30

def unlock
  @f.close
  File.delete( @f.path)
rescue Errno::ENOENT
  #do nothing
end