I’ve used alias_method_chain on top of ActiveRecord associations in a couple of situations lately. It has emerged as kind of a neat pattern, imho.
For Caching
Let’s say that you’ve got some Users who have Roles. These roles don’t change frequently at all, so they are prime candidates for caching.
class User < ActiveRecord::Base
has_many :roles
def roles_with_cache
Rails.cache.fetch("user_roles/#{self.id}", :expires_in => 15.minutes) do
roles_without_cache
end
end
alias_method_chain :roles, :cache
end
When calling User#roles, the aliased method will try to fetch them from the cache first. If they don’t exist there, they’ll be pulled from the database.
For Sharding
If you’re using the excellent DataFabric gem to shard your database, you know that your access (finders, etc.) to the sharded tables is done within a block. We can use the same pattern from above to auto-shard access to these associated objects.
class User < ActiveRecord::Base
has_many :tweets
def tweets_with_shard
self.in_shard { tweets_without_shard }
end
alias_method_chain :tweets, :shard
def in_shard(&block)
DataFabric.activate_shard(:store => shard, &block)
end
end
Fun. What other interesting uses for alias_method_chain on top of ActiveRecord associations have you seen?
February 3, 2009 at 6:22 am
[...] caches_method. This is a plugin I wrote, inspired by one of Brian Dainton’s blog posts. It’s still under development to allow for some more elegant expiry strategies, but [...]