Posted on May 25, 2007 at 8:25 pm

Caching things with acts_as_taggable_on_steroids

RubberDuck on steroids

On today’s chapter of “hacking the hell out of rails plugins” we’re going to talk about how to add caching support for acts_as_taggable_on_steroids.
The plugin is a great improvement over the original (and discontinued) acts_as_taggable, and allow you to add “tagging” support to any model class easily, just by marking it with “acts_as_taggable”:

You will soon notice, however, that your system grows, rubber ducks will get slower and slower to manipulate - specially when you want to list, say, rubber ducks and their related tags, or the number of tags associated to each rubber duck. That is due to the fact that acts_as_taggable doesn’t cache any information on the taggable class (in our case, the glorious rubber ducks).
But don’t panic - addind that support is easy as 1, 2, 3. The code below is from my modified acts_as_taggable.rb, which now supports caching both number of tags per duck, or a cached list of tags:

The main addition here, as you can see, is basically the save_caches() instance method and two class-level variables (@@cache_tags and @@cache_tag_count), that will handle caching of tag count and tags on the taggable class. Making rubber ducks cache is simple:

And there you go: rubber ducks that keep both tag count and list of tags on the rubber_ducks table, with no need to join to the tags/taggings. By the way, don’t forget to add the two fields to your rubber_ducks table.
Obviously, some improvements can be done (you can call the cache attribute tag_list, for instance - but then you’d need to modify methods such as the remote_tag_list, which I really didn’t bother modifying).
Have fun!

Tags:, ,

2 Responses to “Caching things with acts_as_taggable_on_steroids”

  1. fulvio on February 2nd, 2008 at 2:46 am says:

    Hmm, thanks for this!

    However, I get the following error:

    undefined method `delimiter’ for Tag:Class

  2. fulvio on February 2nd, 2008 at 2:53 am says:

    If I replace all instances of Tag.delimiter with “,” (which is what I specified in my environment.rb by doing TagList.delimiter = “,”) it works.

    However it then throws the following error:

    undefined method `parse’ for Tag:Class

Leave a Reply