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]


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.

1 comment:

Anonymous said...

Our physics replica rolex professor was replica rolex struggling to replica rolex draw the class into replica rolex discussion replica rolex of Archimede's rolex principle rolex of water displacement.rolex He told us that rolex Archimede Final Fantasy XI GIL noticedrolex that when replica watches he got into replica watches a pool at the replica watches public bathhouse,replica watches the water replica watches rose spilling replica rolex over the edge. replica rolex Excited at his replica rolex discovery, he ran down replica rolex the street yelling,replica rolex "Eureka, eureka!cheap aion kinah The instructor asked ffxi gil if anyone knew what that meant.