问题
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