Sha256: a9ecff8f274eca1c09d0aa1ed38f10854cc53897d77a1eb8196649cf8e73390b

Contents?: true

Size: 941 Bytes

Versions: 2

Compression:

Stored size: 941 Bytes

Contents

module Restruct
  class Locker < Structure

    REGISTER_LUA   = File.read "#{File.dirname(__FILE__)}/../../lua/register.lua"
    UNREGISTER_LUA = File.read "#{File.dirname(__FILE__)}/../../lua/unregister.lua"

    def lock(key, &block)
      _lock key, false, &block
    end

    def lock!(key, &block)
      _lock key, true, &block
    end

    alias_method :unlock!, :destroy

    alias_method :locked?, :exists?

    def key
      connection.call('HGET', id, 'key')
    end
    alias_method :locked_by, :key

    def to_h
      ::Hash[connection.call('HGETALL', id).each_slice(2).to_a]
    end
    alias_method :to_primitive, :to_h
    
    private

    def _lock(key, exclusive)
      connection.script REGISTER_LUA, 0, id, key, exclusive
      begin
        yield
      ensure  
        connection.script UNREGISTER_LUA, 0, id
      end      
    rescue Restruct::ConnectionError => ex
      raise LockerError.new ex
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
restruct-1.1.0 lib/restruct/locker.rb
restruct-1.0.0 lib/restruct/locker.rb