Rails time zone from URL params

廉价感情. 提交于 2020-01-25 11:24:06

问题


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

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.

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


回答1:


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

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

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.



来源:https://stackoverflow.com/questions/13276001/rails-time-zone-from-url-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!