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
Comments left...
Constants in environment.rb are good. But if you’re going to bother with date formats, you should define them so that they work with Date’s to_s(format) method.
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(:my_date => “d %b %Y”, :my_date_time => “d %b %Y %H:%M”)
Then you can do @object.created_at.to_s(:my_date)
josh at 30 Mar 07 at 00:34
Nice trick especially the module part :)
Ed at 30 Mar 07 at 02:39
thanks guys.
sal at 19 Jul 07 at 21:25
Articles Archive →
Got something to say?