Rails set timezone per request
Sometimes we need to have a request be processed in a particular timezone in Rails. To set a timezone per request in Rails, we can have an around filter that sets timezone, runs the requests and then resets timezone to what it was before the request.
We can set Timezone in Rails with the help of code given below.
This will set the time zone to Asia/Kolkata
.
Problem with setting timezone
The problem with this approach is that it will use the time zone Asia/Kolkata
to the next subsequent Rails requests on the same thread.
Please avoid setting timezone in rails to avoid timezone issues in the Rails application.
Set timezone per request
Add an
around_filter
and set Time.zone
.
This performs following things.
- Store old time zone before setting a timezone for a request.
- Set a new timezone per request in
around_filter
. - Ensure old time zone is restored when the request processing is completed.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox