Natural Date Parsing
The Chronic gem makes it simple.
Sorry for the delay since my last post, but we have been wrapping up the final details of our new website, which is due to launch sometime in the next 10 days or so. During development of our new site, which is built using Ruby on Rails, I’ve come across quite a few interesting Ruby gems and Rails plugins that have been extremely helpful. One great example is the Chronic gem, which provides methods for natural date parsing.
First of all, let’s explain a Ruby gem for those that are unfamiliar with what they are. Ruby is a programming language, just like PHP and Java, which can be extended with various libraries to make life easier. With Ruby, these extensions are called “gems”, which can be installed as easily as typing:
gem install chronic
You will need administrative (sudo) access to the machine you want to install gems on. Typing in the above command will automatically find and install the Chronic gem. Once installed, you can use the methods provided by the Chronic gem in any of your Ruby scripts or Rails applications by simply requiring the gem:
require 'chronic'
So what does Chronic do? This is the real meat of this post, as I have been simply amazed by the methods it provides. It centers around natural date parsing, which is the process of converting common English ways of expressing dates into actual Time objects in Ruby. Consider the usability impact of requiring a user to enter dates in the YYYY-MM-DD format, versus allowing someone to type in a phrase such as “next Thursday”. Both interfaces will require some user training, as will all interfaces, but the one that allows people to express dates as they naturally would is going to be much more useful and efficient.
And that is the magic of the Chronic gem. It allows you to take a string expression of a date and easily convert that into a Time object in Ruby. It’s as simple as passing the string to the chronic object, as in the following example:
Chronic.parse('3rd Wednesday this month')
Chronic will then automatically create a Time object that represents the “third Thursday of this month”. Pretty impressive, and the options are really diverse. Check out the Chronic documentation for more information on the available options for parsing dates. I have been personally impressed, and I like the trend of natural parsing. I like the idea that in the future there will be more support for parsing natural language, whether it be in a search engine or just for dates. Such a simple thing can have a huge impact on usability.