Sha256: 37115a52c6e7ba4b4fa13aae8552fff90b53e6ace994452adc0ba07c2df0cdec

Contents?: true

Size: 840 Bytes

Versions: 9

Compression:

Stored size: 840 Bytes

Contents

# -*- encoding: utf-8 -*-
class LockFile
  attr_accessor :logger, :path, :quiet

  # By default print errors
  @quiet = false

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

  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

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

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

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
bin_script-0.1.8 lib/bin_script/lock_file.rb
bin_script-0.1.7 lib/bin_script/lock_file.rb
bin_script-0.1.6 lib/bin_script/lock_file.rb
bin_script-0.1.5 lib/bin_script/lock_file.rb
bin_script-0.1.4 lib/bin_script/lock_file.rb
bin_script-0.1.3 lib/bin_script/lock_file.rb
bin_script-0.1.2 lib/bin_script/lock_file.rb
bin_script-0.1.1 lib/bin_script/lock_file.rb
bin_script-0.1 lib/bin_script/lock_file.rb