Раздел «Язык Ruby».MakeCached:

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.

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