内容简介:I had thought to write a post on this, but never got around to it.Essentially, this is the practice I use:
Rails better practice for dealing with altering the current process's timezone
In Rails, Prefer `.use_zone` to `.zone=`
I had thought to write a post on this, but never got around to it.
Prathamesh Sonpatki beat me to it :)
Essentially, this is the practice I use:
Time.use_zone(current_user.timezone) do # Do Time and DateTime operations under the auspices of the # current user's timezone setting. Time.current # The current time in the current user's timezone Time.zone.now # Equivalent to the above end
It's better than just supposing that Time.zone
has been set somewhere in the current process, or
that Time.zone
has been set to what the code in the block expects it to be!
In Testing
The biggest source of error that I've encountered for this isn't in requests, but actually in the spec test cases for the product. Some test cases blythely set Time.zone
in a before action, but never reset it in an after action.
If possible, wrap the time zone use inside an around
action:
around(:each) do |example|
Time.use_zone(some_timezone) do
yield example
end
end
With Timecop
Since Timecop is essentially mocking the system clock, you can use it with .use_zone
with impunity.
around do |example|
Timecop.freeze do
@account = Fabricate(:account)
Time.use_zone(account.timezone) do
yield example
end
end
end
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
孵化Twitter
[美]尼克·比尔顿(Nick Bilton) / 欧常智、张宇、单旖 / 浙江人民出版社 / 2014-1 / 49.90元
一个在挣扎中生存的博客平台Odeo,一小撮龙蛇混杂的无政府主义者员工,经历了怎样的涅槃,摇身一变,成为纽交所最闪耀的上市企业Twitter? 一个野心勃勃的农场小男孩,一个满身纹身的“无名氏“,一个爱开玩笑的外交家,一位害羞而又充满活力的极客,这四位各有特色的创始人如何从兢兢业业、每日劳作的工程师,成为了登上杂志封面、奥普拉秀和每日秀的富裕名人?而在Twitter日益茁壮成长的过程中,他们又......一起来看看 《孵化Twitter》 这本书的介绍吧!