| Module | Cachetastic::Cacheable::ClassAndInstanceMethods |
| In: |
lib/cachetastic/cacheable.rb
|
Returns the Cachetastic::Cache object associated with the object. If a cache hasn‘t been defined the one will be created on the fly. The cache for the object is expected to be defined as: Cachetastic::Cacheable::{CLASS_NAME_HERE}Cache
Examples:
class Person
include Cachetastic::Cacheable
end
Person.cache_class # => Cachetastic::Cacheable::PersonCache
class Admin::Person
include Cachetastic::Cacheable
end
Admin::Person.cache_class # => Cachetastic::Cacheable::Admin_PersonCache
# File lib/cachetastic/cacheable.rb, line 41
41: def cache_class
42: n = self.class.name
43: n = self.name if n == "Class"
44: c_name = "Cachetastic::Cacheable::#{n.gsub('::', '_')}Cache"
45: begin
46: return c_name.constantize
47: rescue NameError => e
48: eval %{
49: class #{c_name} < Cachetastic::Cache
50:
51: def self.cache_klass
52: #{n}
53: end
54:
55: end
56: }
57: return c_name.constantize
58: end
59:
60: end
How much did I want to call this method cache?? It originally was that, but in Rails 2.0 they decided to use that name, so I had to rename this method. This method will attempt to get an object from the cache for a given key. If the object is nil and a block is given the block will be run, and the results of the block will be automatically cached.
Example:
class Person
include Cachetastic::Cacheable
def always_the_same(x,y)
cacher("always_the_same") do
x + y
end
end
end
Person.new.always_the_same(1,2) # => 3
Person.new.always_the_same(2,2) # => 3
Person.new.always_the_same(3,3) # => 3
Person.cacher("always_the_same") # => 3
Person.get_from_cache("always_the_same") # => 3
Cachetastic::Cacheable::PersonCache.get("always_the_same") # => 3
Person.cacher("say_hi") {"Hi There"} # => "Hi There"
Person.get_from_cache("say_hi") # => "Hi There"
Cachetastic::Cacheable::PersonCache.get("say_hi") # => "Hi There"
# File lib/cachetastic/cacheable.rb, line 89
89: def cacher(key, expiry = nil)
90: cache_class.get(key) do
91: if block_given?
92: res = yield
93: cache_class.set(key, res, expiry)
94: end
95: end
96: end
Expires the entire cache associated with this objects‘s cache.
Example:
class Person
include Cachetastic::Cacheable
attr_accessor :name
def cachetastic_key
self.name
end
end
Person.set_into_cache(1, "one")
Person.get_from_cache(1) # => "one"
Person.expire_all
Person.get_from_cache(1) # => nil
Person.set_into_cache(1, "one")
Person.get_from_cache(1) # => "one"
Cachetastic::Cacheable::PersonCache.expire_all
Person.get_from_cache(1) # => nil
# File lib/cachetastic/cacheable.rb, line 117
117: def expire_all
118: cache_class.expire_all
119: end