Module: Itrigga::Cache::FileCache

Defined in:
lib/itrigga/cache/itrigga-file_cache.rb

Class Method Summary collapse

Class Method Details

.cache_dirObject



13
14
15
# File 'lib/itrigga/cache/itrigga-file_cache.rb', line 13

def cache_dir
  @cache_dir 
end

.cache_dir=(dir) ⇒ Object



17
18
19
# File 'lib/itrigga/cache/itrigga-file_cache.rb', line 17

def cache_dir=(dir)
  @cache_dir=dir
end

.delete(opts) ⇒ Object



50
51
52
# File 'lib/itrigga/cache/itrigga-file_cache.rb', line 50

def delete(opts)
  File.delete(file_path(opts)) if is_in_cache?(opts)
end

.expired?(opts = {}) ⇒ Boolean

Returns:

  • (Boolean)


58
59
60
61
# File 'lib/itrigga/cache/itrigga-file_cache.rb', line 58

def expired?( opts={} )    
  opts[:timeout_seconds] ||= self.timeout_seconds
  Time.now - File.mtime(file_path(opts)) > opts[:timeout_seconds]
end

.file_path(opts) ⇒ Object

Raises:

  • (ArgumentError)


63
64
65
66
67
68
69
# File 'lib/itrigga/cache/itrigga-file_cache.rb', line 63

def file_path( opts )
  raise ArgumentError.new(":cache_key is required") unless opts[:cache_key]
  
  opts[:cache_dir] ||= self.cache_dir
  
  File.expand_path( File.join(opts[:cache_dir], opts[:cache_key]) )
end

.get(opts) ⇒ Object



42
43
44
# File 'lib/itrigga/cache/itrigga-file_cache.rb', line 42

def get(opts)
  File.open( file_path(opts), 'r' ){ |f| f.read }
end

.is_in_cache?(opts = {}) ⇒ Boolean

Returns:

  • (Boolean)


54
55
56
# File 'lib/itrigga/cache/itrigga-file_cache.rb', line 54

def is_in_cache?( opts={} )        
  File.exists?( file_path(opts) )
end

.put(opts, content) ⇒ Object



46
47
48
# File 'lib/itrigga/cache/itrigga-file_cache.rb', line 46

def put(opts, content)
  File.open( file_path(opts), 'w' ){ |f| f.write(content) }
end

.timeout_secondsObject



21
22
23
# File 'lib/itrigga/cache/itrigga-file_cache.rb', line 21

def timeout_seconds
  @timeout_seconds
end

.timeout_seconds=(secs) ⇒ Object



25
26
27
# File 'lib/itrigga/cache/itrigga-file_cache.rb', line 25

def timeout_seconds=(secs)
  @timeout_seconds = secs
end

.with_cache(opts = {}, &block) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/itrigga/cache/itrigga-file_cache.rb', line 29

def with_cache( opts={}, &block )
  begin
    if is_in_cache?(opts) && !expired?(opts)
      get(opts)
    else
      delete(opts)
      result = block.call
      put( opts, result )
      result
    end
  end
end