Chris Mar's Weblog Blog Different

Friday Oct 24, 2008

I noticed a really interesting feature coming in Rails 2.2 called "Memoization". It means caching the return value of a method. If your method is called multiple times the cache value is returned rather then the executing the method again.

This is something I do in every application for

def current_user
     @current_user ||= User.find(session[:current_user_id])
end

In the new Rails 2.2, you can have the same behavior with the "memoize" declaration

memoize :current_user
def current_user
     User.find(session[:current_user_id])
end

Regardless of how many times I call current_user, Rails will only do one DB query.

This level of caching is very common and we always use it in practice with instance variables and singleton patterns. Its nice to see a declarative way to do this in Rails. Learning a new software term like "Memoization" is a bonus.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed