Sha256: 81016a734091b89cf56c62dda90ed13da5d6813ceb0956513cfb50b94d8ebee6

Contents?: true

Size: 1009 Bytes

Versions: 7

Compression:

Stored size: 1009 Bytes

Contents

require 'tempfile'

module Pitchfork
  class Flock
    Error = Class.new(StandardError)

    def initialize(name)
      @name = name
      @file = Tempfile.create([name, '.lock'])
      @file.write("#{Process.pid}\n")
      @file.flush
      @owned = false
    end

    def at_fork
      @owned = false
      @file.close
      @file = File.open(@file.path, "w")
      nil
    end

    def to_io
      @file
    end

    def unlink
      File.unlink(@file.path)
    rescue Errno::ENOENT
      false
    end

    def try_lock
      raise Error, "Pitchfork::Flock(#{@name}) trying to lock an already owned lock" if @owned

      if @file.flock(File::LOCK_EX | File::LOCK_NB)
        @owned = true
      else
        false
      end
    end

    def unlock
      raise Error, "Pitchfork::Flock(#{@name}) trying to unlock a non-owned lock" unless @owned

      begin
        if @file.flock(File::LOCK_UN)
          @owned = false
          true
        else
          false
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
pitchfork-0.12.0 lib/pitchfork/flock.rb
pitchfork-0.11.1 lib/pitchfork/flock.rb
pitchfork-0.11.0 lib/pitchfork/flock.rb
pitchfork-0.10.0 lib/pitchfork/flock.rb
pitchfork-0.9.0 lib/pitchfork/flock.rb
pitchfork-0.8.0 lib/pitchfork/flock.rb
pitchfork-0.7.0 lib/pitchfork/flock.rb