Class: WithTimedCache::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/with_timed_cache/cache.rb

Direct Known Subclasses

JSONCache, YAMLCache

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

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

#keyObject (readonly)

Returns the value of attribute key.



6
7
8
# File 'lib/with_timed_cache/cache.rb', line 6

def key
  @key
end

#locationObject (readonly)

Returns the value of attribute location.



6
7
8
# File 'lib/with_timed_cache/cache.rb', line 6

def location
  @location
end

#max_ageObject (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_extensionObject



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_nameObject



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

Returns:

  • (Boolean)


20
21
22
# File 'lib/with_timed_cache/cache.rb', line 20

def exists?
  File.exists? @location
end

#filenameObject



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

#readObject



24
25
26
# File 'lib/with_timed_cache/cache.rb', line 24

def read
  Marshal.load(File.read(@location))
end

#stale?Boolean

Returns:

  • (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