Module: Itrigga::Cache::ClassMethods

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

Instance Method Summary collapse

Instance Method Details

#cache_log(text, opts = {}) ⇒ Object



149
150
151
152
# File 'lib/itrigga/cache/cache.rb', line 149

def cache_log(text, opts = {})
  message = "[CACHE] [#{opts[:backend] }] #{text}"
  defined?(Rails.logger) && Rails.logger ? Rails.logger.info(message) : puts(message)
end

#caching_enabled?(opts = {}) ⇒ Boolean

Returns:

  • (Boolean)


100
101
102
# File 'lib/itrigga/cache/cache.rb', line 100

def caching_enabled?(opts = {})
  Itrigga::Cache.instance(opts).enabled == true
end

#delete_from_cache(key, opts = {}) ⇒ Object



138
139
140
141
142
143
144
145
146
# File 'lib/itrigga/cache/cache.rb', line 138

def delete_from_cache(key, opts = {})
  return nil unless caching_enabled?(opts)
  begin
    cache_log "Deleting key #{key}", opts  
    Itrigga::Cache.instance(opts).delete key
  rescue Exception => e
    nil
  end
end

#get_from_cache(key, opts = {}) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/itrigga/cache/cache.rb', line 108

def get_from_cache(key, opts = {})
  return nil unless caching_enabled?(opts)
  cache_log "get_from_cache key: #{key},  opts: #{opts.inspect}" if opts[:debug]
  begin
    Itrigga::Cache.instance(opts).get key
  rescue Memcached::NotFound => not_found
    # we dont care 
    nil
  rescue Exception => e
    cache_log "Exception in get_from_cache: #{e.message}"
    nil
  end
end

#set_to_cache(key, value, opts = {}) ⇒ Object



124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/itrigga/cache/cache.rb', line 124

def set_to_cache(key, value, opts = {})
  raise "Cache not Enabled" unless caching_enabled?(opts)
        
  cache_log "set_to_cache key: #{key}, value: #{value}, opts: #{opts.inspect}" if opts[:debug]
  begin
    Itrigga::Cache.instance(opts).set key, value, opts
  rescue Exception => e
    cache_log "Exception in set_to_cache: #{e.message}"
  end
    
  value
end

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



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/itrigga/cache/cache.rb', line 75

def with_cache(opts = {}, &block)
  require_param(opts, :key)
  
  # if no cache then just return whatever the block gives us
  unless caching_enabled?(opts)
    cache_log "Cache not enabled!", opts
    return block.call
  end
  
  # see if the key is already in cache
  value = get_from_cache(opts[:key], opts)
  
  # if no match then call the block and save result in cache
  unless value
    cache_log "Key '#{opts[:key]}' missing! Calling block and setting in cache", opts
    value = block.call
    set_to_cache(opts.delete(:key), value, opts) rescue value # incase memcache crashes or whateversolr1-internal-itrigga.dyndns-ip.com solr1-internal-itrigga.dyndns-ip.com            
  else
    cache_log "Key '#{opts[:key]}' found in cache!", opts
  end
    
  value
end