http://podloni.co.cc Rebecca’s Ramblings » ruby

Archive for the ‘ruby’ Category

“Time” columns and Rails

Thursday, January 3rd, 2008

In SQL, there is a data type TIME which holds time of day information without date information. There is no equivalent class in Ruby. Rails (ActiveRecord) deals with this by adding some dummy date data and using the standard Ruby Time class. Currently the dummy date used is 2000-01-01, though since I can’t find any documentation on this, I guess it could be changed to something else in the future.

This means you can run into some odd issues if you aren’t careful when comparing values from SQL TIME columns with times in your code.

For example, if you have a record r in your database with the value “13:30:00″ stored in a column called arrival_time of SQL data type TIME:

Time.parse("2000-01-01 13:30") == r.arrival_time       # unless the dummy date AR uses has changed

"13:30:00" == r.arrival_time_before_type_cast

Time.parse("13:30") != r.arrival_time         # unless today is 1st January 2000

Quick tip: ruby’s inject method

Wednesday, August 22nd, 2007

If you’ve been using the online version of the Pickaxe book as your ruby reference, you won’t know about this very useful little method in the Enumerable module. It allows you to do something cumulative with each item in your Enumerable object.

For example, to sum prices in an array of items ordered:

order = [item0, item1, item2]
total_price = order.inject(0) {|sum, item| sum + item.price}

instead of:

order = [item0, item1, item2]
total_price = 0
order.each {|item| total_price += item.price}

Notes:

  • The method parameter is the starting value for whatever the cumulative value is - in this case, sum.
  • The first block parameter is the cumulative value, the second is the current object from the Enumerable.
  • The value returned by the statement in the block is set as the starting value for the next object from the Enumerable.

For more details, see this article on ruby arrays on thinkvitamin.com.