Localized range formats with Rails – a post at Steven Luscher’s blog

Date range

Here’s an implementation of Range#to_formatted_s that lets you retrieve range formats from your locale bank.

It’s true that you can write your own range conversions and add them to ::Range::RANGE_FORMATS. Those conversions could refer to translations in your locale bank, but I’d prefer to see what the range formatter is doing without having to look in two places. I wanted a formatter that would do something like this, where :fancy can represent a different Proc depending on the current locale:

>> (Time.current..Time.current+1.hour).to_s :fancy
=> "Monday, February 16th, 2009 between 6:00pm and 7:00pm PST"

First, I implemented a version of Range#to_formatted_s that’s I18n aware (thanks clemens!).

config/initializers/range_conversions.rb:

# Allows you to do things like (Time.current..Time.current+1.day).to_s :local_format
# where range.format.local_format is an entry in one of your locale files
::Range.class_eval do
  def to_formatted_s(format = :default)
    formats = ::Range::RANGE_FORMATS
    formatter = formats[format]
 
    unless formatter
      formatters = I18n.translate(:'range.formats', :raise => true) rescue {}
      formatter  = formatters[format]
    end
 
    formatter.respond_to?(:call) ? formatter.call(self.begin, self.end) : to_default_s
  end
  alias_method :to_s, :to_formatted_s
end

Next, I edited my locale file:

config/locales/en.rb:

{ :en => {
 
  # Range
  :range => {
    :formats => {
      :fancy => lambda { |start_time, finish_time|
        start_format = "%B #{start_time.day.ordinalize}, %Y between %l:%M%p"
        finish_format = "%l:%M%p %Z"
 
         "#{I18n.localize(start_time, :format => start_format)} and #{I18n.localize(finish_time, :format => finish_format)}"
      }
    }
  }
 
} }

And there you have it; fancy-formatted date ranges with localization.

Tags: , ,

be the first person to comment on this post:

Want to include some code? Use Pastie and stick the link into your comment. Linebreaks, block quotes, and preformatted code blocks will be removed.

Please make an attempt to prove that you’re still human before submitting your comment.

If you've written a post of your own in response to this one, feel free to trackback from your own site.

be the first person to comment on this entry.