Out of the box, Rails’
Let’s start with Chronic for parsing date/time values into something you can store in a database. First, install the gem:
Chronic’s usage is very straightforward. Let’s fire up
script/console to have a look:
So rather than requiring users to use Rails’ default pulldown-based date picker, or enter data in forced formats (like
Say you’re developing a cooking site or project management tool and want to allow users to enter spans of time like “35 minutes,” “1 hour 15 minutes,” “1:30,” or “2 days” and store them in a consistent format. Enter Chronic Duration—it works like Chronic, but for stretches of time as opposed to actual dates or times. After parsing the entry, the duration is stored in the database as the number of seconds. First, install the gem:
Let’s look at it in action using
And so on. Chronic Duration also provides an output method:
Experimenting with the gems in the console is one thing, but how do we put them to use in a Rails application? Here’s how I do it. Going back to the idea of a project tracker, say I’ve got a model named
Task with a due date and an estimated time field. It might look like this:
Don’t forget to include Chronic and Chronic Duration in your
config/environment.rb file, and restart your application.
There are a few ways you could use
ChronicDuration::output in your application’s views—you could either override the accessor in the model by adding something like
or use it in a view helper along the lines of
and use the helper in your views. It depends on what you need to do with the data, so experiment within your application to see what works best.
Chronic doesn’t include a function to return a date value in a pretty format—just use Ruby’s strftime method to handle that.
I stand with the Black community against systemic racism, police violence and brutality, intolerance, and hate in the United States and worldwide. We must all demand better from our leaders, and ourselves. Stop tolerating intolerance.
While you're here, please consider making a donation to Black Girls CODE, who do great, important work to provide opportunity to underprivileged girls interested in tech, or any organization working toward equity and safety for all, not just the privileged. Thank you.
If you liked my series on practical advice for adding reliable tests to your Rails apps, check out the expanded ebook version. Lots of additional, exclusive content and a complete sample Rails application.
Ruby on Rails news and tips, and other ideas and surprises from Aaron at Everyday Rails. Delivered to your inbox on no particular set schedule.