Validate Dates in Your Models 3

Posted by Bob Silva Fri, 08 Sep 2006 06:11:00 GMT

mojombo in #caboose, just released his first version of Chronic, a new Ruby Gem for natural language processing of Dates and Times.
gem install chronic

irb:>
Chronic.parse('tomorrow')
    #=> Mon Aug 28 12:00:00 PDT 2006

Chronic.parse('monday', :context => :past)
    #=> Mon Aug 21 12:00:00 PDT 2006

Chronic.parse('this tuesday 5:00')
    #=> Tue Aug 29 17:00:00 PDT 2006

Chronic.parse('this tuesday 5:00', :ambiguous_time_range => :none)
    #=> Tue Aug 29 05:00:00 PDT 2006

Chronic.parse('may 27th', :now => Time.local(2000, 1, 1))
    #=> Sat May 27 12:00:00 PDT 2000

Chronic.parse('may 27th', :guess => false)
    #=> Sun May 27 00:00:00 PDT 2007..Mon May 28 00:00:00 PDT 2007

The thing I find really nice is that if you pass it a malformed date, it returns nil. This means, in your model validations, you can add:
require 'chronic'

class Meeting < ActiveRecord::Base

  def validation
    errors.add :meeting_date, 'is not a valid date' if Chronic.parse(meeting_date.to_s).nil?
  end

end
Comments

Leave a response

  1. d. Taylor Singletary about 8 hours later:
    This is terrific. Thanks. Ruby is the single easiest and most pleasant language I've ever dealt with for manipulating Time.
  2. Kevin about 15 hours later:
    What about the other way? ;) 9/9/2006 is tomorrow, one day from now, next Saturday, etc. etc. etc. (Seriously though, great work... it even knows fortnights!)
  3. Adam T. 3 months later:
    I'm not entirely sure I'm going to get much of a response here, it seems good to bring up. Something I'm running into is that at the point where you've hit your validation (possibly by overriding the validate() method), your target attribute (meeting_date, in this case) has already been typecast to its database type. Assuming that type is "datetime," this becomes a problem because Chronic.parse WILL return nil on a string like, "Thu Dec 14 16:34:00 -0800 2006."
Comments