alias_method_chaining your AR associations (for fun and profit?)

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?

Posted in ruby. Tags: . 1 Comment »

One Response to “alias_method_chaining your AR associations (for fun and profit?)”

  1. 5 quick things to make your Rails app faster Says:

    [...] 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 [...]


Leave a Reply