ActiveSupport adds many conveniences to standard classes. to_s on times/dates is one of these.
Instead of using strftime you can use to_formatted_string (aliased as to_s) – with many useful defaults.
>> t = Time.now
=> Fri Jul 11 23:07:37 +0100 2008
>> t.to_s(:short)
=> "11 Jul 23:07"
>> t.strftime('%d %b %H:%M')
=> "11 Jul 23:07"
I want to display dates using the time_ago_in_words helper – but display any dates older than a week as a normal date.
Time::DATE_FORMATS accepts procs to do the formatting – so with a little bit of coercion we can use the helper in our proc. Put the following in config/initializers/time_formats.rb
class Helper
extend ActionView::Helpers::DateHelper
end
Time::DATE_FORMATS[:ago] = lambda { |time| time >= 7.days.ago ? "#{Helper.time_ago_in_words(time)} ago": time.to_s(:short) }
gives you
>> 1.day.ago.to_s(:ago)
=> "1 day ago"
>> 10.days.ago.to_s(:ago)
=> "01 Jul 23:32"
One good reason not to use time_ago_in_words like this is that it makes anywhere you display dates like that less cacheable (if you want accurate dates). I’ll look into how we could instead use javascript to implement the time_ago_in_words in browser, not sacrificing cacheability in another post.