Class: LitmusPaper::Cache
- Inherits:
-
Object
- Object
- LitmusPaper::Cache
- Defined in:
- lib/litmus_paper/cache.rb
Instance Method Summary collapse
- #_entry(ttl, value) ⇒ Object
- #get(key) ⇒ Object
-
#initialize(location, namespace, ttl) ⇒ Cache
constructor
A new instance of Cache.
- #set(key, value) ⇒ Object
Constructor Details
#initialize(location, namespace, ttl) ⇒ Cache
Returns a new instance of Cache.
7 8 9 10 11 12 |
# File 'lib/litmus_paper/cache.rb', line 7 def initialize(location, namespace, ttl) @path = File.join(location, namespace) @ttl = ttl FileUtils.mkdir_p(@path) end |
Instance Method Details
#_entry(ttl, value) ⇒ Object
47 48 49 |
# File 'lib/litmus_paper/cache.rb', line 47 def _entry(ttl, value) "#{Time.now.to_f + ttl} #{YAML::dump(value)}" end |
#get(key) ⇒ Object
37 38 39 40 41 42 43 44 45 |
# File 'lib/litmus_paper/cache.rb', line 37 def get(key) return unless File.exists?(File.join(@path, key)) File.open(File.join(@path, key), "r") do |f| f.flock(File::LOCK_SH) entry = f.read expires_at, value = entry.split(" ", 2) expires_at.to_f < Time.now.to_f ? nil : YAML::load(value) end end |
#set(key, value) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/litmus_paper/cache.rb', line 14 def set(key, value) return unless @ttl > 0 filename = File.join(@path, key) if File.exist?(filename) File.open(filename, "r+") do |f| f.flock(File::LOCK_EX) f.rewind f.write(_entry(@ttl, value)) f.flush f.truncate(f.pos) end else temp = Tempfile.new("#{key}_init", @path) begin temp.write(_entry(@ttl, value)) temp.flush ensure temp.close end FileUtils.mv(temp.path, filename) end end |