Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Time.zone during a request: Thread Safe?

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.

like image 588
Tyler Gannon Avatar asked Mar 16 '13 16:03

Tyler Gannon


1 Answers

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.

like image 73
Frederick Cheung Avatar answered Nov 17 '22 22:11

Frederick Cheung