Setting Time.zone during a request: Thread Safe?

我怕爱的太早我们不能终老 提交于 2019-12-10 12:48:11

问题


I'd like to let users of my app specify a time zone, and then set their time zone at the beginning of each request. In Rails, AFAICT, this is done by setting the singleton object:

Time.zone = "America/Los_Angeles"

My understanding of best practices is that, generally speaking, a singleton should be set ONCE. For example in the application configuration.

From an answer to a similar question, someone suggests setting it in the ApplicationController

class ApplicationController < ActionController::Base
  before_filter :set_timezone
  def set_timezone
    # current_user.time_zone #=> 'London'
    Time.zone = current_user.time_zone if current_user && current_user.time_zone
  end
end

Is this safe? Or do I run a risk of having one thread affect another? I will try running a test of this but it's not the easiest test scenario ever so I thought I should see if someone has already done this.


回答1:


If you look at the code where this is implemented you can see that the current zone is stored in a thread local variable, so each thread can set Time.zone without interfering with other threads.



来源:https://stackoverflow.com/questions/15451637/setting-time-zone-during-a-request-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!