Sha256: c8c3de533d663f0d2c13619419e359c49edf26c7457c30a81872dd25c8fee232

Contents?: true

Size: 1.01 KB

Versions: 4

Compression:

Stored size: 1.01 KB

Contents

# frozen_string_literal: true
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

4 entries across 4 versions & 1 rubygems

Version Path
pitchfork-0.16.0 lib/pitchfork/flock.rb
pitchfork-0.15.0 lib/pitchfork/flock.rb
pitchfork-0.14.0 lib/pitchfork/flock.rb
pitchfork-0.13.0 lib/pitchfork/flock.rb