class LockFile

Attributes

logger[RW]
path[RW]
quiet[RW]

Public Class Methods

new(path, logger = nil) click to toggle source
# File lib/bin_script/lock_file.rb, line 7
def initialize(path, logger = nil)
  if path == nil
    raise "file path cannot be nil"
  end
  @path = path
  @logger = logger || $logger
end

Public Instance Methods

lock(waiting_unlock = false) click to toggle source
# File lib/bin_script/lock_file.rb, line 15
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) click to toggle source
# File lib/bin_script/lock_file.rb, line 36
def log(str)
  return if @quiet
  if @logger
    @logger.warn str
  else
    print str
  end
end
unlock() click to toggle source
# File lib/bin_script/lock_file.rb, line 29
def unlock
  @f.close
  File.delete( @f.path)
rescue Errno::ENOENT
  #do nothing
end