2012-04-26 82 views
2

我有一个模型,它具有纬度,经度和日期时间属性,我希望能够计算该位置的时区并为模型的每个单独实例进行设置。这里是我写的代码,以获得时区有我缺少的东西?根据位置计算时区[Rails]

require 'nokogiri' 
require 'open-uri' 

before_validation :set_current_time_zone 

def set_current_time_zone 
    Time.zone = find_timezone_based_on_location 
end 

def find_time_zone_based_on_location 
    url = "http://www.earthtools.org/timezone-1.1/#{self.latitude}/#{self.longitude}" 
    doc = Nokogiri::XML(open(url)) 
    offset = doc.at_xpath('//offset').text().to_i 
    if offset == -5 
    "Eastern Time (US & Canada)" 
    .... 
    elsif offset == -8 
    "Pacific Time (US & Canada)" 
    end 
end 

有什么,我失踪,为什么这不是设置正确的时间?

回答

0

我能得到的代码通过改变set_current_time_zone以下工作:

def set_current_time_zone 
    self.attributeActiveSupport::TimeZone[find_time_zone_based_on_location].local_to_utc(self.attribute) 
end 

这将找到正确的时区,然后将该时间转换为UTC。

1

我不确定是否真的想在模型的每个实例中设置时区。根据从控制器访问模型的MVC,在控制器级别设置time_zone应该足够好。将时区设置为控制器级别后,所有与时间相关的计算都将在过滤器中设置的time_zone中为该请求处理。以下是代码。

def set_time_zone 
    old_time_zone = Time.zone 
    Time.zone = find_time_zone_based_on_location 
    yield 
    ensure 
    Time.zone = old_time_zone 
    end 

而在要设置时区的控制器中,您需要定义环绕过滤器。 find_time_zone_based_on_location(由你上面定义的)可以辅助方法application_controller

around_filter :set_time_zone