Friday, January 29, 2010

Make your rails application DRY with constants

Constants help with consistency, they easily allow you to keep your code DRY.
One of the ways I utitilise constants is to standardise the date formatting I use across an app.
For example, in environment.rb I will create a module to contain my date format constants:

module Dates
DATE_FORMAT = "%d% %b %Y"
DATE_TIME_FORMAT = "#{DATE_FORMAT} %H:%M"
end

The module just groups them nicely together. To use the constants I will write the following:

@object.created_at.strftime(Dates::DATE_FORMAT)
@object.created_at.strftime(Dates::DATE_TIME_FORMAT)

Remember you will need to restart your server after making any changes to environment.rb

No comments: