Gem MakeCached
Provides method
make_cached
for creating methods caching their values:
make_cached(method_name, options={}) # => cache
For example line
make_cached :get_value_cached, :method => :get_value, :expire_in => 100 # => cache
defines new method :get_value_cache, which is the version of original method :get_value
with caching of calculated values.
Usually called in class scope. You can use the following options.
-
:expire_in
specifies time (in seconds) cached values will expire in. Float. Optional. Synonyms are :timeout
and :recache_after
.
-
:method
specifies original method name. Symbol. Optional (omit it if cached method has the same name as original).
-
:limit
specifies maximum number of values to cache. Integer. If this limit is reached, then old&unpopular values are removed from cache. Optional. Default is infinity.
-
:cache_in
specifies scope (:global
, :class
, :object
). Cache may be stored in global scope, in class scope, or in object scope. Optional. Default is :object
.
-
:if
conditional block on the method's args and calculated value. If returns false, then do not use/cache value.
Examples
require 'make_cached'
def fib(n)
(n == 0 || n == 1) ? 1: fib(n-1) + fib(n-2)
end
puts fib(100) # argh! it's too long
make_cached :fib
fib(100) # works fast now
puts fib_cache.inspect # you can access cached values
class User < ActiveRecord::Base
class <<self
make_cached :count_cached, :method => :count, :expire_in => 1.minute
end
end
class User < ActiveRecord::Base
class <<self
# cache most active 100 users
# refresh user data from database each 5 minutes
make_cached :get,
:method => :find_by_id,
:expire_in => 5.minutes,
:limit => 100,
:if => {|args, value| !value.nil?}
end
end
--
ArtemVoroztsov - 06 Jul 2008