Hacking Rails Plugins

Using the Acts as Taggable On plugin to add categories to a model class, I wanted to override the to_param method and place the name attribute in the url. The plugin, installed as a gem, source shouldn’t need to be hacked in order to accomplish this. The solution is to add a plugin into the RAILS_ROOT/vendor/plugins directory and append the plugin name with _hack. This will, because of an alphabetical load order, allow you to reopen the any class in the plugin. In my example

# RAILS_ROOT/vendor/plugins/acts_as_taggable_on_hack/init.rb
Tag.class_eval do
  to_param
    "#{id}-#{name.gsub(/[^a-z0-9]+/i, '-'/)
  end
end

Got this tip from http://errtheblog.com/posts/67-evil-twin-plugin.

Override to_param method in model to get pseudo permalinks without any work

There are a number of permalink plugins for Rails, http://www.seoonrails.com/even-better-looking-urls-with-permalink_fu, is a good one that I’ve used before. However, this involves informing the model class (has_permalink :title), adding a route, using the route in your views and controllers and of course running some migrations. If you’re willing to get 99% of the functionality for 0% of the work, just override the to_param method in your model.

This assumes you have an attribute for your model that you’d like to use for your permalink, but that’s it.

#app/models/post.rb

class Post < ActiveRecord::Base
  def to_param
    "#{id}-#{title.gsub(/[^a-z0-9]+/i, '-').downcase}"
  end
end

That’s it. You don’t have to change your controllers, routes or views. Your URL will look something like

/posts/45-pseudo-permalinks-with-rails

Active record will strip all alpha characters from the params[:id] variable leaving you with just the integer value of your model.

So long as you don’t mind that integer in the url, it’s an easy solution that you can bake in at any point w/out having to touch the rest of your application code.