in-rails-prefer-use_zone-to-zone

栏目: IT技术 · 发布时间: 4年前

内容简介: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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

计算广告

计算广告

刘鹏、王超 / 人民邮电出版社 / 2015-9-1 / 69.00元

计算广告是一项新兴的研究课题,它涉及大规模搜索和文本分析、信息获取、统计模型、机器学习、分类、优化以及微观经济学等诸多领域的知识。本书从实践出发,系统地介绍计算广告的产品、问题、系统和算法,并且从工业界的视角对这一领域具体技术的深入剖析。 本书立足于广告市场的根本问题,从计算广告各个阶段所遇到的市场挑战出发,以广告系统业务形态的需求和变化为主线,依次介绍合约广告系统、竞价广告系统、程序化交易......一起来看看 《计算广告》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试