Archive for September 2009

L33t Links #20

42

What happens when I’m bored:

david@david-laptop:~/code$ irb
irb(main):001:0> class Integer
irb(main):002:1>   def inspect
irb(main):003:2>     if self == 42
irb(main):004:3>       "The answer to life, the universe, and everything"
irb(main):005:3>     else
irb(main):006:3*       super
irb(main):007:3>     end
irb(main):008:2>   end
irb(main):009:1> end
=> nil
irb(main):010:0> 42
=> The answer to life, the universe, and everything

L33t Links #19

L33t Links #18

I don’t have time to post links neither Saturday, nor Sunday. So I’m posting them now.

L33t Links #17

L33t Links #16

Funny Simpsons quote from an episode I watched yesterday: Bart meats a bunch of robots. “Hi, we’re abandoned robots too.” “I am not a robot, I’m a human!” “Ooh, how is it to feel?” “I said I’m a human, not a girl.”

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!

L33t Links #15

L33t Links #14

It’s been quiet the last couple of days…

L33t Links #13