URL参数的Rails时区 [英] Rails time zone from URL params

查看:85
本文介绍了URL参数的Rails时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图允许非登录用户更改一天中的时间显示,看来最好的方法是通过url中的参数.我有:

I'm trying to allow non-signed-in users to change a time of day display, and it seems like the best way would be through params in the url. I have:

class ApplicationController < ActionController::Base
  around_filter :use_time_zone

  private
    def use_time_zone(&block)
      Time.use_zone((params[:time] || Time.zone), &block)
    end
end

这对于像'www.mysite.com?time=Hawaii'之类的东西很有用

And this works great for something like 'www.mysite.com?time=Hawaii'

但是,它无法处理一些更复杂的内容(例如,东部时间(美国和加拿大)"),而且在地址栏中看起来也很糟糕.

However, it cannot handle some of the more intricate ones (e.g. 'Eastern Time (US & Canada)'), plus this looks bad in the address bar.

有没有一种方法可以将带DST的UTC偏移量(或其他缩写形式,例如"PDT")与参数一起使用?

Is there a way to simply use UTC offset with DST (or any other abbreviated form like 'PDT') with params?

推荐答案

我通过变通办法解决了这个问题,希望其他人会发现它有用.

I solved this with a workaround, hopefully others may find it useful.

我创建了一个帮助程序,用于根据时区名称的前2个字母生成键/值对:

I created a helper to generate key/value pairs based on first 2 letters of time zone name:

# helpers/application_helper.rb
(...)
def tz_mapping
  tzs = Hash.new
  ActiveSupport::TimeZone.us_zones.reverse.each do |tz|
    tzs[tz.name.to_s.first(2).downcase] = tz
  end
  tzs
end

然后,我可以通过params传递这些缩写,然后在控制器中进行选择:

Then I can pass those abbreviations in via params and pick it up in the controller:

# controllers/application_controller.rb
(...)
around_filter :use_time_zone

private

def use_time_zone(&block)
  zones = { 'ha' => 'Hawaii',
            'al' => 'Alaska',
            'pa' => 'Pacific Time (US & Canada)',
            'ar' => 'Arizona',
            'mo' => 'Mountain Time (US & Canada)',
            'ce' => 'Central Time (US & Canada)',
            'ea' => 'Eastern Time (US & Canada)',
            'in' => 'Indiana (East)' }

  Time.use_zone((zones[params[:tz]] || Time.zone), &block)
end

所以一个简单的视图可能看起来像

So a simple view might look like

<% tz_mapping.each do |k,v| %>
  <%= link_to v, root_path + "?tz=#{k}" %><br />
<% end %>

其中提供了每种情况的链接,并且可以根据需要使用.

Which gives links to each scenario, and can be used as needed.

这篇关于URL参数的Rails时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆