I have a simple method running in a private method in my model :
def with_time_zone(zone)
@old_time_zone = Time.zone
Time.zone = self.account.timezone
Chronic.time_class = Time.zone
yield
ensure
Time.zone = @old_time_zone
Chronic.time_class = @old_time_zone
end
I use it like this :
with_time_zone(account.timezone) do
Time.parse(@time)
end
However, when I run my tests, the begin with the timezone set to EST, but when it comes time to compare the times, the Time.zone will be set to which ever timezone was last used in that block. Thus telling me that the ensure method isn’t being called, and the Time.zone is not being reset.
Anyone know why this might be occurring?
Perhaps, you are making nested calls to the method? Since you don’t maintain a stack, the first nested call will cause the earlier value of
@old_time_zoneto be lost.If that’s what’s going on, just stop using an instance variable, and use a local variable instead (no
@sign). Each nested invocation of the method has its own local variables, and they’re still in scope in theensureblock.