Class: WithTimedCache::Cache
- Inherits:
-
Object
- Object
- WithTimedCache::Cache
- Defined in:
- lib/with_timed_cache/cache.rb
Instance Attribute Summary collapse
-
#key ⇒ Object
readonly
Returns the value of attribute key.
-
#location ⇒ Object
readonly
Returns the value of attribute location.
-
#max_age ⇒ Object
readonly
Returns the value of attribute max_age.
Class Method Summary collapse
Instance Method Summary collapse
- #exists? ⇒ Boolean
- #filename ⇒ Object
-
#initialize(key, opts = {}) ⇒ Cache
constructor
A new instance of Cache.
- #read ⇒ Object
- #stale? ⇒ Boolean
- #write(data) ⇒ Object
Constructor Details
#initialize(key, opts = {}) ⇒ Cache
Returns a new instance of Cache.
8 9 10 11 12 13 14 |
# File 'lib/with_timed_cache/cache.rb', line 8 def initialize(key, opts = {}) @key = key @max_age = opts[:max_age] || 1.hour @location = opts[:location] || File.join("tmp", filename) @location = File.join(@location, filename) if File.directory?(@location) self end |
Instance Attribute Details
#key ⇒ Object (readonly)
Returns the value of attribute key.
6 7 8 |
# File 'lib/with_timed_cache/cache.rb', line 6 def key @key end |
#location ⇒ Object (readonly)
Returns the value of attribute location.
6 7 8 |
# File 'lib/with_timed_cache/cache.rb', line 6 def location @location end |
#max_age ⇒ Object (readonly)
Returns the value of attribute max_age.
6 7 8 |
# File 'lib/with_timed_cache/cache.rb', line 6 def max_age @max_age end |
Class Method Details
.file_extension ⇒ Object
39 40 41 |
# File 'lib/with_timed_cache/cache.rb', line 39 def self.file_extension @file_extension ||= self.local_class_name.sub(/Cache$/, "").downcase end |
.local_class_name ⇒ Object
43 44 45 |
# File 'lib/with_timed_cache/cache.rb', line 43 def self.local_class_name @local_class_name ||= self.to_s.split("::").last rescue self.to_s end |
Instance Method Details
#exists? ⇒ Boolean
20 21 22 |
# File 'lib/with_timed_cache/cache.rb', line 20 def exists? File.exists? @location end |
#filename ⇒ Object
32 33 34 35 36 37 |
# File 'lib/with_timed_cache/cache.rb', line 32 def filename extension = self.class.file_extension filename = "#{@key}_cache" filename += ".#{extension}" unless extension.empty? filename end |
#read ⇒ Object
24 25 26 |
# File 'lib/with_timed_cache/cache.rb', line 24 def read Marshal.load(File.read(@location)) end |
#stale? ⇒ Boolean
16 17 18 |
# File 'lib/with_timed_cache/cache.rb', line 16 def stale? File.mtime(@location) < @max_age.ago end |
#write(data) ⇒ Object
28 29 30 |
# File 'lib/with_timed_cache/cache.rb', line 28 def write(data) File.open(@location, 'w') { |f| f.write Marshal.dump(data) } end |