17 February, 2008

Updates to active_support_hacks

I've made a couple of updates to my active_support_hacks

First: DateRange#include?(other)

This accepts a Date, Time or another TimeRange. It assumes inclusive range ends

4.days.ago.until(1.day.ago).include?(2.days.ago)                    #  => true
4.days.ago.until(1.day.ago).include?(3.days.ago.until(2.days.ago)   #  => true
5.hours.from_now.until(10.hours.from_now).include?(6.days.from_now) #  => false

Second: Pretty Date Formatters

These generate human-readable times and dates, like "9 hours from now" and "earlier this week"

f = ActiveSupport::CoreExtensions::Time::PrettyNumericDateFormatter.new
f.call(5.hours.ago)       # => "5 hours ago"
f.call(37.days.ago)       # => "1 month ago"

f = ActiveSupport::CoreExtensions::Time::PrettySimpleDateFormatter.new
f.call(5.hours.ago)       # => "earlier today"
f.call(55.days.from_now)  # => "later this year"

You can load these into the ActiveSupport formatting code like so:

require 'active_support/core_ext/time/pretty_numeric_date_formatter'
require 'active_support/core_ext/time/pretty_simple_date_formatter'

#each formatter must either respond to #call(Date) and #call(Time) or be a String for strftime

formatters = {
  :pretty_numeric => ActiveSupport::CoreExtensions::Time::PrettyNumericDateFormatter.new,
  :pretty_simple => ActiveSupport::CoreExtensions::Time::PrettySimpleDateFormatter.new
}
formatters[:pretty] = formatters[:pretty_numeric]
formatters[:default] = formatters[:pretty]

ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(formatters)
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(formatters)

I have that in my Rails app in /config/initializers/date_formats.rb. If you don't want to override the default formatting of dates, don't include the formatters[:default] = formatters[:pretty] line. By including a [:default] in the hash, all ActionViews will automatically use this formatter.

No comments: