Module: Cacheify
- Defined in:
- lib/cacheify.rb
Overview
Enables caching of method calls
Class Method Summary collapse
-
.cache ⇒ Object
:nodoc:.
-
.cache_store=(store_option) ⇒ Object
Set cache store to be used by Cachify (or leave it be to use defaults).
- .included(obj) ⇒ Object
Instance Method Summary collapse
-
#cacheify(*symbols) ⇒ Object
Cache results of methods.
Class Method Details
.cache ⇒ Object
:nodoc:
19 20 21 |
# File 'lib/cacheify.rb', line 19 def self.cache # :nodoc: @cache_store ||= defined?(Rails) ? Rails.cache : ActiveSupport::Cache.lookup_store(:file_store, "tmp/cacheify") end |
.cache_store=(store_option) ⇒ Object
Set cache store to be used by Cachify (or leave it be to use defaults).
The default is FileStore tmp/cacheify or, if you’re running inside Rails app, whatever Rails is using.
Parameters
store options as understood by ActiveSupport::Cache#lookup_store
15 16 17 |
# File 'lib/cacheify.rb', line 15 def self.cache_store=(store_option) @cache_store = ActiveSupport::Cache.lookup_store(store_option) end |
.included(obj) ⇒ Object
51 52 53 |
# File 'lib/cacheify.rb', line 51 def self.included(obj) obj.extend Cacheify end |
Instance Method Details
#cacheify(*symbols) ⇒ Object
Cache results of methods.
Parameters
-
method names to cache
-
optionally, last argument can be a hash of options passed to ActiveSupport::Cache::Store for caching.
Example
cache_method :big_calculation, :expires_in => 5.minutes
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/cacheify.rb', line 32 def cacheify(*symbols) (self.is_a?(Class) ? self : ).class_eval do = symbols. symbols.each do |method| non_cached_method = "_non_cached_#{method}".to_sym return if method_defined?(non_cached_method) # cached already, skip it alias_method non_cached_method, method define_method(method) do |*args, &block| cache_name = Digest::MD5.hexdigest "#{self.class.name}#{method}#{args.inspect}" marshalled_result = Cacheify.cache.fetch(cache_name, ) do send(non_cached_method, *args, &block) end end end end end |