Module: CacheMethod::ClassMethods
- Defined in:
- lib/cache_method.rb
Overview
All Classes (but not instances), get the .cache_method
method.
Instance Method Summary collapse
-
#cache_method(method_id, ttl = nil) ⇒ Object
Cache a method.
-
#cache_method_clear_on(method_id, cache_method_clear_id) ⇒ Object
Clear a cache method once another method is called.
Instance Method Details
#cache_method(method_id, ttl = nil) ⇒ Object
Cache a method. TTL in seconds, defaults to whatever’s in CacheMethod.config.default_ttl
Note: Remember to define #as_cache_key
on any object whose instance methods might get cached.
Note 2: Check out CacheMethod.config.default_ttl… the default is 24 hours.
Example:
class Blog
def get_latest_entries
# [...]
end
cache_method :get_latest_entries
end
95 96 97 98 99 100 101 |
# File 'lib/cache_method.rb', line 95 def cache_method(method_id, ttl = nil) original_method_id = "_cache_method_#{method_id}" alias_method original_method_id, method_id define_method method_id do |*args, &blk| ::CacheMethod::CachedResult.new(self, method_id, original_method_id, ttl, args, &blk).fetch end end |
#cache_method_clear_on(method_id, cache_method_clear_id) ⇒ Object
Clear a cache method once another method is called. Useful in situations where you want to clear a cache whenever another method is callled, commonly an update.
Example:
class Blog
def get_latest_entries
# [...]
end
def update_entries
# update happens
end
cache_method_clear_on :update_entries, :get_latest_entries
end
117 118 119 120 121 122 123 124 125 |
# File 'lib/cache_method.rb', line 117 def cache_method_clear_on(method_id, cache_method_clear_id) original_method_id = "_cache_method_clear_on_#{method_id}" alias_method original_method_id, method_id define_method method_id do |*args, &blk| cache_method_clear cache_method_clear_id send(original_method_id, *args, &blk) end end |