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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With