1

我有一个设置时区的 webapp

post_controller.rb

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

现在,我没有在注册时从用户那里获取 time_zone,而是想知道如何从客户端动态设置时区并将其设置在 before_filter 中。我试图使用detect_timezone_rails gem。gem 提供了一种访问客户端时区的简单方法,只需从 js 文件中调用这样的函数即可。

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

现在,上面的代码自动设置你的隐藏字段输入或选择输入,但我想知道你是否可以简单地使用函数调用保存到会话并从 Rails 服务器检索它。我猜当用户第一次访问该站点时,可以设置时区,并且可以使用会话值来设置其余访问的时区。我认为可以使用会话值在前置过滤器中设置时区。作为 javascript 的新手,我不确定如何访问 Rail 的加密 cookie 存储来设置值。这可能吗?如果是这样,我该怎么做?提前致谢,

4

2 回答 2

3
#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
于 2013-01-15T16:09:24.063 回答
1

我们这样做有些不同。如果我们想从 JS 收集时区,我们使用gon gem在 Rails 端设置一个变量。然后,我们在客户端上有 JS 代码检查该变量,如果设置,则使用jstimezonedetect脚本返回的时区字符串向端点发送 XHR(就像 OP 所做的那样),该脚本返回 IANA 时区键。最后,为了将其转换为 Rails 3.2.19 时区名称,我们做了ActiveSupport::TimeZone::MAPPING.invert[iana_key]. 花了一些步骤来解决这个问题,希望它对某人有所帮助。

于 2015-10-22T21:46:53.140 回答