0

On my VPS (Ubuntu 10.04LTS), I have ree-1.8.7-2011.03 and ruby-1.9.2-p180 installed through RVM. My problem is that when I call Time.now in ree-1.8.7(irb), I get Thu May 12 12:16:50 +0200 2011, when I do the same in ruby-1.9.2(irb), I get 2011-05-12 12:17:44 +0200.

The problem is the ree version of the date is unusable in my rails queries (The SQL generated is just plain broken). Formatting the time using strftime in every single query is not an option at the moment, and neither is switching to 1.9.2, so I need your help to figure out why this is happening and fix it.

Thanks for any help!

Marc
  • 438
  • 1
  • 4
  • 15
  • How do you pass dates to the queries? Aren't you using AR's parameter interpolation? – Mladen Jablanović May 12 '11 at 10:43
  • In most cases I am, but some of the larger queries are just a whole lot easier to read when I use string interpolation. – Marc May 12 '11 at 13:41
  • Ok, just remember that you can also use `:name` form with Hash, instead of `?` with Array. Readable enough, even more than ordinary string interpolation IMO. – Mladen Jablanović May 12 '11 at 14:44
  • Thanks, I've known about that for a while, but I haven't used it yet. Ill give it a try and see how it looks. Thanks! – Marc May 12 '11 at 19:49

2 Answers2

7

This is not a REE issue. Ruby 1.9.2 changes the default format for Time#to_s.

$ rvm use 1.8.7
ruby-1.8.7-p334 :001 > Time.now
# => Thu May 12 12:42:35 +0200 2011 

$ rvm use 1.9.2
ruby-1.9.2-p180 :001 > Time.now
# => 2011-05-12 12:42:44 +0200 

It's a good practice to never rely on the default Time#to_s format but always use a custom helper or method to format a date output otherwise you have no control on how the information are displayed.

Formatting the time using strftime in every single query is not an option at the moment

Not only it should be an option, it should have been your first choice. I strongly encourage you to fix the existing code to use a custom formatting method.

A temporary workaround would be to override Ruby 1.8.7 Time#to_s method to use a custom format. However, making such this change might break other libraries.

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • Thanks, I have kind of come to the same conclusion in the past few minutes, thought I had no idea about that change between 1.8 and 1.9. I now know I have to use the strftime, it was only not an immediate option. – Marc May 12 '11 at 10:51
  • But is there a difference between interleaving the time into the where clause with #{Time.now} in the string, and doing a "?" replacement? – Marc May 12 '11 at 10:59
3

How about something like this in your config/initializers/app.rb

Time::DATE_FORMATS[:default] = "Your preferred date format"
Aditya Sanghi
  • 13,370
  • 2
  • 44
  • 50
  • Placing Time::DATE_FORMATS[:default]= "%F %T %Z" in my initializer had no effect, but no matter, I have decided to use strftime in all my queries as indicated by Simone Carletti. Thanks! – Marc May 12 '11 at 13:09