The most opportune gem ever?

May 8th, 2008 by ymendel 0 comments »

We can all agree that most development stems from people wanting to make something easier, right? I’m not just talking about programming, but that’s what I do, something I know well, and what I’m specifically talking about here. And it comes from wanting to make something easier.

And sometimes that comes in the form of wanting to stamp out an annoyance.

The past couple of days saw me working a lot with trying to get specific times on specific dates, cleaning up code that originally looked like

day_time = Time.local(date.year, date.month, date.day, input[:day_hour], input[:day_minute])
night_time = Time.local(date.year, date.month, date.day-1, input[:day_hour], input[:day_minute])

And while I knew it worked, I really hated that date.day-1 thing. Maybe I’m just a tight-ass, but it looks and feels so wrong, especially in Ruby. I preferred to be specific, which meant instead making the code look like

day_time = Time.local(date.year, date.month, date.day, input[:day_hour], input[:day_minute])
prev_date = date - 1
night_time = Time.local(prev_date.year, prev_date.month, prev_date.day, input[:day_hour], input[:day_minute])

That soothed one (slight) annoyance, but the major one was still there. What I really wanted to do was have something like

Time.local(date, hour, minute)

I did a little homework, looking through documentation, searching around, asking around, but there didn’t seem to be anything like this in Ruby. It surprised me, and when I realized even Facets didn’t have it I felt kind of worried and dirty. Was I heading into the dark side where even Trans dared not tread?

I cast my worries aside and pushed on, knowing what I wanted and that it’d be fairly easy to create. Really, the longest and hardest work came in doing research to see if there was already a wheel out there I was going to reinvent, and after that I had to think of a name.

So I give you timely. I already did this once today, so here I’ll just paste a section of the README.

require 'timely'

some_date = Date.today - 5      # => 2008-05-03
some_date.at_time(3, 5, 13)     # => Sat May 03 03:05:13 -0500 2008

# arguments are optional
some_date.at_time(13)           # => Sat May 03 13:00:00 -0500 2008

some_time = Time.now - 345678   # => Sun May 04 13:40:22 -0500 2008
some_time.on_date(2001, 6, 18)  # => Mon Jun 18 13:40:22 -0500 2001

# if you have objects corresponding to the times/dates you want
some_time.on_date(some_date)    # => Sat May 03 13:40:22 -0500 2008
some_date.at_time(some_time)    # => Sat May 03 13:40:22 -0500 2008

# if you like typing less
some_time.on(some_date)         # => Sat May 03 13:40:22 -0500 2008
some_date.at(some_time)         # => Sat May 03 13:40:22 -0500 2008

Obligatory github link: http://github.com/flogic/timely/tree/master
Obligatory tracking link: http://tasks.ogconsultin.gs/projects/show/timely

Leave a Reply