Merb and Chronic: Natural Language Date Parsing
This assumes you’ve already got started with merb, and that you are using datamapper as your orm.
NOTE: This DOESN’T validate the chronicfied date yet so strange words like gobblygoob will still get passed, and the form will get saved.
0.Install chronic gem
sudo gem install chronic
1. In init.rb make sure you include the chronic gem as well as the following gems.
1 | dependencies "merb-more", "merb_helpers", "merb-assets", "dm-timestamps", "dm-validations", "chronic" |
2. In your model.rb chronicfy the date with the datamapper before_valid? hook
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class Post include DataMapper::Resource property :id, Integer, :serial => true # A :serial property is an auto-incrementing key property :date, Date property :title, :String property :description, String property :created_at, DateTime property :updated_at, DateTime # see http://datamapper.org/docs/validations.html though there must be a way to refactor this cleaner validates_with_method :must_be_chronic def must_be_chronic if Chronic.parse(self.date).nil? [false, "is not a valid date. Try removing any commas."] else return true end end before :valid?, :chronicfy def chronicfy self.date = Chronic.parse(self.date) end end |
3. In your view, change the date field to a text_field.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <h1>Posts controller, new action</h1> <p>Edit this file in <tt>app/views/posts/new.html.erb</tt></p> <%= form_for @post, :class => "post_form", :action => url(:posts) do %> <%= partial("posts/form") %> <% end =%> # here's the _form.rhtml partial <%= error_messages_for @post %> <p> <%= text_field :date, :label => "Date<br />" %> </p> <p> <%= text_field :title, :label => "Title<br />" %> </p> <p> <%= text_field :description, :label => "Description<br />" %> </p> |
