My first gem: Chronorails!

Post date: 04-Sep-2013 05:47:43

Chronic and Chronic Duration are super useful gems for parsing natural language descriptions of dates into Ruby objects (DateTimes and Fixnums, respectively). They're both popular with Rails developers, but when new developers ask about integration into their app, the answer is usually 'roll your own'.

After adding support by hand in this manner a few times I knew it was time to break my work out into something I could re-use. Thus, Chronorails. Let's start with an example.

For a hypothetical Rails model:

class RomanticMeeting < ActiveRecord::Base

attr_accessible :length, :start # Integer and DateTime DB fields, respectively

include Chronorails::ChronicAccessors

chronic_field :start, :required => true

chronic_duration_field :length

end

…include the accessors module, and configure Chronorails to wrap your attributes with either Chronic or Chronic Duration virtual attributes.

Then in your form:

<%= f.text_field :chronic_start %>

<%= f.text_field :chronic_duration_length %>

…you can use the virtual attributes for your fields, entering natural language date and duration information that will be parsed into the regular fields (or will generate validation errors).

The ‘required’ option prevents setting the attributes with blank values; the ‘validates’ option controls the generation of validators (defaults to true) and the ‘accessible’ option controls the generation of Rails 3 ‘attr_accessible’ calls (also defaults to true.)

I've workshopped this concept and code with a few developers, now I'm hungry for feedback from a wider field. Let me know if it suits your needs, and preferably, if the code inside makes sense. Fork it on github and have a play. :)