Creating a minimal Rails plugin

$ rails myapp
$ cd myapp
$ script/generate plugin myplugin

To load the plugin automatically add this line in vendor/plugins/myplugin/init.rb

require 'myplugin'

Now most action happens in vendor/plugins/myplugin/lib/myplugin.rb. Suppose we’d like to add a class method to ActiveRecord:

class << ActiveRecord::Base
  def set_my_stuff(option_name, value)
    @my_stuff ||= {}
    @my_stuff[option_name] = value
  end
end

Now in the model definition we can use the plugin this way:

class Foo < ActiveRecord::Base
  set_my_stuff :bar, 123
end

A useful technique we might need is backing up the class methods if we’re redefining them. The alias_method method is quite useful:

alias_method :original_foo, :foo
def foo(*args) # new one!
  options = args.is_a?(Hash) ? args.pop : {}
  original_foo(options)
end