The Railscast on Time Zones has some sample code that lets you set a thread-local, per-request time zone with a before_filter:
# controllers/application.rb before_filter :set_user_time_zone private def set_user_time_zone Time.zone = current_user.time_zone if logged_in? end
Problem is, the current user’s time zone will leak across to the next request on the same thread. If the next one is by a logged-out user, all times displayed on that next request will show in the first user’s time zone.
To prevent this, use an around_filter:
around_filter :set_time_zone private def set_time_zone old_time_zone = Time.zone Time.zone = current_user.time_zone if logged_in? yield ensure Time.zone = old_time_zone end
You might be tempted to combine the first two lines of set_time_zone into one line with the comma assignment syntax and add “if logged_in?” to the one line in the ensure clause. Don’t do it. If you did that, the user’s time zone would leak out to the next request when the user logs out.
I’ve submitted a Rails patch to use this method in the sample code for the Time.zone= docs.