Posts Tagged ‘plugin’

L33t Links #84

Running a website costs money which is why I’ve added some slots for Google AdSense ads on this blog and in its feed, namely at the bottom of every blog post, near the top of the sidebar on every page, and at the bottom of each feed item. They’re fairly small and colored similarly to the rest of the blog to make them as discrete as possible. Thanks for your understanding!

L33t Links #78

L33t Links #77

The first beta of Rails 3 is out! These links are all related to the release:

Un-related to the release:

L33t Links #51

It’s been a while, but finally I can present a new bunch of links to you:

L33t Links #48

L33t Links #45

L33t Links #44

L33t Links #43

L33t Links #42

#42! This blog post is the answer to everything! Or not!

Introducing Virtual Attribute Cache

This is really old news but I’m aiming to have one post per open source project on this blog.

Virtual Attribute Cache is the ultimate way to cache Active Record virtual attributes. The idea is simple. Say, for example, you have a first_name and a last_name column. Then you might have a full_name virtual attribute that joins first_name and last_name plus a full_name column in your database which stores the cached value of the full_name virtual attribute. With va_cache that would be accomplished like this:

class Person < ActiveRecord::Base
  cached_virtual_attribute(:full_name, :expire_if => Proc.new { |p| p.first_name_changed? || p.last_name_changed? }) do
    [first_name, last_name].join(' ')
  end
end

Basically, you need to provide va_cache with three things:

  1. The name of the virtual attribute to cache.
  2. When to expire the cache (the Proc will be evaluated in a before_save callback.)
  3. How to calculate the value of the virtual attribute.

If you don’t like to have Proc’s in the middle of your method calls you can use this alternative syntax:

class Person < ActiveRecord::Base
  cached_virtual_attribute :full_name, :expire_if => :first_name_or_last_name_changed do
    [first_name, last_name].join(' ')
  end

  def first_name_or_last_name_changed?
    first_name_changed? || last_name_changed?
  end
end

Final notes:

  • Don’t use va_cache with simple stuff like full names, obviously.
  • If you pass a symbol to the :expire_if a question mark will be appended automatically.
  • Seriously, go look at the source code. It’s extremely simple.

That’s it. Enjoy!