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

Constant Summary collapse

DIR =
::File.join ::Dir.tmpdir, 'lock_method'

Instance Method Summary collapse

Constructor Details

#initializeDefaultStorageClient

Returns a new instance of DefaultStorageClient.



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

def initialize
  @mutex = ::Mutex.new
  ::FileUtils.mkdir(DIR) unless ::File.directory?(DIR)
end

Instance Method Details

#delete(k) ⇒ Object



49
50
51
# File 'lib/lock_method/default_storage_client.rb', line 49

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

#flushObject



53
54
55
56
57
# File 'lib/lock_method/default_storage_client.rb', line 53

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

#get(k) ⇒ Object



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

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



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

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