I created a rails app that helps parents keep track of how their children sleep. For it to work correctly, I had to maintain different time zones. To avoid annoying the user with time zones, I created a little javascript that adds a hidden field to the login form, including the time zone offset. Here is the code
var timeZoneField = $("input[name='user_tz_offset']"); if (timeZoneField.length) { var browserDate = new Date(); var timeZoneOffsetSeconds = (browserDate.getTimezoneOffset() * 60) * -1; $(timeZoneField).val(timeZoneOffsetSeconds); }
With the data from this field, I set Time.zone to any city that matches this offset. Something like this generates a time zone
user_time_zone = ActiveSupport::TimeZone.[](params[:user_tz_offset].to_i) session[:user_time_zone] = user_time_zone
Finally, I set the time zone in the ApplicationController.
def set_user_time_zone if (session[:user_id]) Time.zone = session[:user_time_zone] else Time.zone = config.time_zone end end
It all depends on the input functionality that I wrote myself. However, I knew that I would need to use a more advanced user management system later, since my own code is neither good nor safe (at first I focused on other functions).
Now I installed the program, and it works well for logging in and logging out, most of the other functions of the site work. But I donβt know how to approach time zone support using my user management system.
One idea is to override SessionController in Devise, add validation for this hidden timezone field, and add its value to user_session. But I feel wary of this, it seems like a bad idea.
Is there a better way to add this functionality without forcing the user to add time zone information during registration?
Thanks!