Autonomous Machine

Using blocks in Rails custom date formats

A not-so-well known feature of ActiveSupport is its ability to handle blocks as definitions for custom date and time formats. Here's one I just added to a project to give nice short dates, stripping out any leading zeros:

  :shorty => lambda {|date| date.strftime("%m/%d/%y").gsub(/0?(\d+)\/0?(\d+)\/(\d+)/, '\1/\2/\3')}

You can drop that in your environment.rb; a better option is to place it in a file inside config/initializers.