Tuesday, June 3, 2008

Extending core Classes in Ruby on Rails

While I was tinkering with our agile tracker tool, I had the need of a first_of_month method that would tell me the first day of the month of any particular day. In a less flexible language, you are limited to the choices of:

  1. write a 'utility' class which is just a bucket of useful methods - not very elegant and ugly too use.
  2. extend the built-in Date class and add your own methods - not very convenient because you have to remember too use the class 'MyDate' everywhere
What Ruby lets you do is simply add your own methods to existing classes! This is exactly what's needed.

To do this in rails, simple create a new file in your 'lib' directory called date_extension.rb and put the following code in it.

class Date

  def first_of_month
    return Date.new(self.year, self.month, 1)


To get Rails to load this extra method, you need to add the following line to your 'config/environment.rb' file.

require 'date_extension.rb'

Thats it! You'll need to restart Rails to see the change, but then you can use the new method anywhere in your controllers or templates. For example:

first_of_month = Date.today.first_of_month

You can do the same with String and add your favourite starts_with? or whatever methods.

No comments: