Using constants in environment.rb in Ruby on Rails
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
About
Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.
Contact
my name at gmail.com
More snippets
Take a look in the archive
Need a website?
Contact my employer. Make sure to check out our portfolio of work.
Hosting
I recommend hostingrails.com
3 comments made
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)
Nice trick especially the module part :)
thanks guys.
Got something to say?