Recent News

Time Parseable

Nobody likes dropdowns. datetime_select and date_select? Ugly troupes of unwieldy elements, each of them. They form a line and rudely spit lists of numbers at you. Who wants that? I know how to type a date. Rails knows how to parse a date. Time.parse, let’s be friends!

$ script/plugin install git://github.com/cementhorses/time_parseable.git

Now, let’s say we have this object filled with timestamp attributes that we need to manage…

# create_table do |t|
#   t.timestamp :published_at, :archived_at
# end
class NewsItem < ActiveRecord::Base
  time_parseable
end

What? NewsItem now has published_at_string and archived_at_string? Yup. And on assignment, they are automatically parsed with Time.parse.

news_item.published_at_string = 'April 30, 2008'
news_item.published_at # => Wed Apr 30 00:00:00 -0000 2008

If you’re only parsing the published_at column, and magic is looking a bit too expensive for you, scope things down.

time_parseable :published_at

Wonderful.

Wait a second! Time.parse, you’re a good friend, but what are you doing?

Time.parse('Cement Horses') == Time.now # => true

Yes, “Cement Horses” is now, but I only want dates for dates. time_parseable, please work this out.

news_item.archived_at_string = 'Cement Horses'
news_item.archived_at # => nil
news_item.errors.on(:archived_at) # => 'is invalid'

Let’s just throw things in a form_for, and time_parseable will do the rest.

<%= f.label :published_at_string %>
<%= f.text_field :published_at_string %>

The field, once assigned, will return a strftime-formatted result. We can choose the format (but we must choose wisely—it should be able to parse to the same result).

time_parseable :format => '%I:%M %p on %b %d, %Y'

That’s it for now. Cutting down the form fields, one time at a time.



Comments are closed

cementhorses.com

Categories

Cement Horses Pics

Archives