Crazy Little Hacks

Some little hacks and random thoughts on what interests me at the moment in the area of computer science.

Adding a Method to All Records

If there are some methods you wish all of your Active Record instances would have, the easiest way to add them is to monkey patch. Here is how to add a random method that retrieves a random record from a table:

module ActiveRecordBaseExtension
  def random
    self.find :first, 
              :offset => (self.count * rand).to_i
  end
end
ActiveRecord::Base.extend ActiveRecordBaseExtension

This code can be appended to lib/rails_extension.rb which should be required in the config/environment.rb file:

require 'lib/rails_extension.rb'

Comments