Skip to content

Using constants in environment.rb in Ruby on Rails

Posted on 29 March 2007

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

View the snippets archive ››

3 comments made

josh commented on 30 Mar 07 at 00:34

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)

Ed commented on 30 Mar 07 at 02:39

Nice trick especially the module part :)

sal commented on 19 Jul 07 at 21:25

thanks guys.

Got something to say?

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