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...
-
gem install chronic
Then, in your views, use a text_field for your date...
-
<% form_for :model do |f| %>
-
<% f.text_field :date_attr_name %>
-
<% 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...
-
require 'chronic'
-
-
class MyModel <ActiveRecord::Base
-
-
def before_save
-
self.date_attr_name = Chronic.parse(self.date_attr_name_before_type_cast) if self.date_attr_name_before_type_cast
-
end
-
-
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.
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.
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 ”
May 30th, 2008 at 3:01 pm
[...] Short and SWEET tutorial for chronic [...]