Class: LitmusPaper::Cache
- Inherits:
-
Object
- Object
- LitmusPaper::Cache
- Defined in:
- lib/litmus_paper/cache.rb
Instance Method Summary collapse
- #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.
5 6 7 8 9 10 |
# File 'lib/litmus_paper/cache.rb', line 5 def initialize(location, namespace, ttl) @path = File.join(location, namespace) @ttl = ttl FileUtils.mkdir_p(@path) end |
Instance Method Details
#get(key) ⇒ Object
23 24 25 26 27 28 29 30 31 |
# File 'lib/litmus_paper/cache.rb', line 23 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
12 13 14 15 16 17 18 19 20 21 |
# File 'lib/litmus_paper/cache.rb', line 12 def set(key, value) return unless @ttl > 0 File.open(File.join(@path, key), "a") do |f| f.flock(File::LOCK_EX) f.rewind f.write("#{Time.now.to_f + @ttl} #{YAML::dump(value)}") f.flush f.truncate(f.pos) end end |