# Web::Persistent::Lock::Flock
# Copyright(c) 2002 MoonWolf <moonwolf@moonwolf.com>
module Web
  class Persistent
    module Lock
      class Flock
        def initialize(persistent_id, options={})
          @persistent_id = persistent_id
          @dir    = options[:dir]    || '/tmp'
          prefix  = options[:prefix] || 'lock_'
          @path   = File.join(@dir, prefix + persistent_id)
          @f      = nil
          @locked = false
        end

        def lock
          @locked = true
          @f = @f || open(@path,'w')
          @f.flock(File::LOCK_EX)
          if block_given?
            yield
            unlock
          end
        end

        def unlock
          raise unless @f
          @f.flock(File::LOCK_UN)
          @locked = false
        end

        def delete
          begin
            File.unlink(@path)
            if @f
              @f.close
              @f = nil
            end
          rescue Errno::ENOENT
          end
        end
      end # Flock
    end # Lock
  end # Persistent
end # Web
