Agile Tortoise

Greg Pierce’s blog

« Using the Google Maps API geocoder in Servoy      Fat Frank on TV »

Rails and Chronic, easy ’smart’ date fields

There are quite a few Ruby on Rails plugins to give you nice Calendar drop downs for date selection...but, I'm much more partial to the style of fuzzy date entry you see in a lot of apps now, allowing you to enter common strings and have the app figure out the date -- ie, "next friday", "tomorrow", etc. With a pointer from Mike yesterday to the excellent Chronic gem, I was on my way.

Chronic does all the hard work, just install it...

CODE:
  1. gem install chronic

Then, in your views, use a text_field for your date...

RUBY:
  1. <% form_for :model do |f| %>
  2. <% f.text_field :date_attr_name %>
  3. <% end %>

In your model, you'll want to then use Chronic to parse the pre-cast value of the date attribute using the _before_type_cast methods...

RUBY:
  1. require 'chronic'
  2.  
  3. class MyModel <ActiveRecord::Base
  4.  
  5.   def before_save
  6.     self.date_attr_name = Chronic.parse(self.date_attr_name_before_type_cast) if self.date_attr_name_before_type_cast
  7.   end
  8.  
  9. end

I expect I'm going to find that I need to tweak this a little -- and I'm pretty sure I'll want to write a helper that will give the user a AJAX preview of the parsed date before the submit the form, but, it definitely beats the lousy Rails built-in date_select method.

  • Share/Save/Bookmark

Wednesday, January 23rd, 2008 at 4:24 pm and is filed under Ruby on Rails. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

3 Responses to “Rails and Chronic, easy ’smart’ date fields”

  1. Scott Says:
    April 4th, 2008 at 9:57 am

    Thank you. Thank you. Excellent short and sweet tutorial for this. Helps clear things up for how to use Chronic.

  2. Jesse Says:
    April 17th, 2008 at 4:09 pm

    Tx for the helpful tutorial.

    In line 2 of the second example, I think that the code has to be ”

  3. Scott Motte » Blog Archive » How to do date, datefields, datetime like 30boxes Says:
    May 30th, 2008 at 3:01 pm

    [...] Short and SWEET tutorial for chronic [...]

Leave a Reply