Class: LockMethod::DefaultStorageClient

Inherits:
Object
  • Object
show all
Defined in:
lib/lock_method/default_storage_client.rb

Overview

:nodoc: all

Defined Under Namespace

Classes: Entry

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeDefaultStorageClient

Returns a new instance of DefaultStorageClient.



23
24
25
26
27
28
# File 'lib/lock_method/default_storage_client.rb', line 23

def initialize
  @mutex = ::Mutex.new
  dir = ::File.expand_path ::File.join(::Dir.tmpdir, 'lock_method')
  ::FileUtils.mkdir(dir) unless ::File.directory?(dir)
  @dir = dir
end

Instance Attribute Details

#dirObject (readonly)

Returns the value of attribute dir.



21
22
23
# File 'lib/lock_method/default_storage_client.rb', line 21

def dir
  @dir
end

Instance Method Details

#delete(k) ⇒ Object



51
52
53
# File 'lib/lock_method/default_storage_client.rb', line 51

def delete(k)
  ::FileUtils.rm_f path(k)
end

#flushObject



55
56
57
58
59
# File 'lib/lock_method/default_storage_client.rb', line 55

def flush
  ::Dir["#{dir}/*.lock"].each do |path|
    ::FileUtils.rm_f path
  end
end

#get(k) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/lock_method/default_storage_client.rb', line 30

def get(k)
  path = path k
  @mutex.synchronize do
    if ::File.exist?(path) and (entry = ::Marshal.load(::File.read(path))) and not entry.expired?
      entry.v
    end
  end
rescue
  $stderr.puts %{[lock_method] Rescued from #{$!.inspect} while trying to get a lock}
end

#set(k, v, ttl) ⇒ Object



41
42
43
44
45
46
47
48
49
# File 'lib/lock_method/default_storage_client.rb', line 41

def set(k, v, ttl)
  entry = Entry.new ttl, v
  @mutex.synchronize do
    ::File.open(path(k), 'wb') do |f|
      f.flock ::File::LOCK_EX
      f.write ::Marshal.dump entry
    end
  end
end