I’ve got a Rails 3.2.6 app running on Ruby 1.8.7. The app is configured to use central European time (i.e. UTC+2) as its time zone, and in my initializers, I monkey-patch Time and DateTime with some custom functionality.
The odd thing is, that in my monkey-patched methods, the Time/DateTime instances act as if they’re UTC (but using the time zone-adjusted value), but elsewhere in the app they respect the time zone config.
So, as an example, in config/initializers/monkey_patching.rb I have the following
module MonkeyPatching
def foo
inspect
end
end
class Time
include MonkeyPatching
end
class DateTime
include MonkeyPatching
end
Now, elsewhere in the app (or in the rails console), here’s what I get
model.created_at.inspect #=> "Mon, 24 Sep 2012 15:06:34 CEST +02:00" (correct!)
model.created_at.foo #=> "Mon Sep 24 15:06:34 UTC 2012" (all wrong!)
So, calling inspect “directly” on model.created_at gives me the correct, timezone-adjusted result. But calling the patched-in method foo – which also just calls inspect! – treats the time as UTC, even though it isn’t.
To add to my confusion, this only happens with model attributes. I.e. in the rails console, I get identical – and correct – results for DateTime.now.inspect and for DateTime.now.foo. But doing the same for a DateTime attribute, give me the strange behavior seen above.
Any idea why this happens (and how to fix it)?
Rails uses
ActiveSupport::TimeWithZonefor time attributes, not regular RubyTime. Try to patchActiveSupport::TimeWithZonetoo.