Rails Time/Date formatting with lambda
By now, most people using Rails are aware that you can do things like this to conveniently format time:
1 2 3 4 5 6 7 | # config/initializers/date_time_formats.rb Time::DATE_FORMATS.merge!( :full => '%B %d, %Y at %I:%M %p', :md => '%m/%d', :mdy => '%m/%d/%y', :time => '%I:%M %p' ) |
Then you can do things like Time.now.to_s(:full) and so on. Nice and DRY. But what if you needed to apply a little bit of logic to determine how to represent your date/time? Well, you can do that pretty easily using lambda:
1 2 3 4 5 6 7 8 9 | Time::DATE_FORMATS.merge!( :friendly => lambda { |time| if time.year == Time.now.year time.strftime "%b #{time.day.ordinalize}" else time.strftime "%b #{time.day.ordinalize}, %Y" end } ) |
Pretty handy. This may be common knowledge to all of you Rails experts, but I didn’t realize this for a while, and I thought it was worth mentioning.

Topher Fangio Friday, 13 Nov, 2009 Posted at 11:21AM
This is awesome! I actually didn’t even know how to do the original merge, the lambda just makes it awesome :-)