Extending a Plugin within rails

Image by

Image by kqedquest

Have you ever wanted to add a method to a class that belonged to a plugin? Well the other day while I was working on articlips.com, I found myself in that position. I am using the acts_as_taggable_on plugin and wanted to memoize a call I was making a lot in various outputs:
<%= tag.name.titleize =>
This is one of those problems I could have solved several ways:

  • Focus on normalizing the data on input
  • Use a helper to accomplish the same goal
  • Cache the page/partial output
  • Not worry about it at all, as this is probably not worth the performance gains per effort invested (at the moment I’m sure there’s plenty more I can optimize)

However it was more out of curiosity that I pursued solving it the way that I initially set out to do.   My first attempt was simply creating a class of the same name in my models folder, but that didn’t have the effect I wanted as (I believe) because the way rails loads classes, it overwrote the class definition instead of adding to it.

At this point I knew there had to be a better way than just modifying the code in the vendor/plugins folder.   Turns out the solution is to add the class/file in the initializers folder as that is the correct time to augment the class during rails initialization.  In hindsight,  pretty obvious.  However since I’m not familiar with the underlying mechanisms of rails as much as I’d like to be, I think I’ve generally overlooked the initializers folder.

1 thought on “Extending a Plugin within rails

Leave a Reply

Your email address will not be published. Required fields are marked *