简体   繁体   中英

Setting timezone on Rails from clientside using javascript

I have a webapp that sets timezone

post_controller.rb

before_filter :set_time_zone
def set_time_zone
  Time.zone = user.time_zone
end

Now, instead of getting the time_zone from the user at registration, I was wondering how I'd set the timezone dynamically from the client side and set it in the before_filter. I was trying to use detect_timezone_rails gem . The gem provides an easy way to access clientside timezone, simply by calling the function like this from js file.

$(document).ready(function(){
    $('#your_input_id').set_timezone(); 
});

Now, the above code automatically sets your hiddenfield input or select input, but I was wondering if you could simply use the function call to save to session and retrieve it from Rails server. I guess when the user first visits the site, the timezone can be set and the session value can be used to set timezone for the rest of the visit. I'd think it'd be possible to use the session value to set timezone in the before filter. Being pretty new to javascript, I'm not sure how to access Rail's encrypted cookie store to set the value. Is this possible? if so, how can I do this? thanks in advance,

#javascript
function readCookieValue(cookieName)
{
  return (result = new RegExp('(?:^|; )' + encodeURIComponent(cookieName) + '=([^;]*)').exec(document.cookie)) ? decodeURIComponent(result[1]) : null;
}

$(document).ready(function(){

if(readCookieValue("time_zone") === null) {
  $.post('/set_time_zone',
       { 'offset_minutes':(-1 * (new Date()).getTimezoneOffset())});
}

#controller:
def set_time_zone
  offset_seconds = params[:offset_minutes].to_i * 60
  @time_zone     = ActiveSupport::TimeZone[offset_seconds]
  @time_zone     = ActiveSupport::TimeZone["UTC"] unless @time_zone
  if @time_zone
    cookies[:time_zone] = @time_zone.name if @time_zone
    render :text => "success"
  else
    render :text => "error"
  end
end

We did this somewhat differently. We use the gon gem to set a variable on the Rails side if we want to collect the timezone from JS. Then we have JS code on the client that examines that variable, and if set, does an XHR post to an endpoint (like the OP did) with the timezone string as returned by the jstimezonedetect script, which returns an IANA timezone key. Finally, to convert this to a Rails 3.2.19 timezone name, we did ActiveSupport::TimeZone::MAPPING.invert[iana_key] . It took a few steps to figure this out, hope it helps someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM