Skip to content
This repository
Browse code

delegate unknown timezones to TZInfo

  • Loading branch information...
commit 2c148cd96aeb9f0bd22f2c130b8b009ebd37e2b7 1 parent de7925d
Santiago Pastorino spastorino authored
17 activesupport/lib/active_support/values/time_zone.rb
@@ -293,13 +293,15 @@ def period_for_local(time, dst=true)
293 293 end
294 294
295 295 def tzinfo
296   - @tzinfo ||= find_tzinfo
  296 + @tzinfo ||= TimeZone.find_tzinfo(name)
297 297 end
298 298
299 299 # TODO: Preload instead of lazy load for thread safety
300   - def find_tzinfo
  300 + def self.find_tzinfo(name)
301 301 require 'tzinfo' unless defined?(TZInfo)
302   - ::TZInfo::Timezone.get(MAPPING[name])
  302 + ::TZInfo::Timezone.get(MAPPING[name] || name)
  303 + rescue TZInfo::InvalidTimezoneIdentifier
  304 + nil
303 305 end
304 306
305 307 unless const_defined?(:ZONES)
@@ -364,7 +366,6 @@ def find_tzinfo
364 366 end
365 367 ZONES.sort!
366 368 ZONES.freeze
367   - ZONES_MAP.freeze
368 369
369 370 US_ZONES = ZONES.find_all { |z| z.name =~ /US|Arizona|Indiana|Hawaii|Alaska/ }
370 371 US_ZONES.freeze
@@ -395,7 +396,7 @@ def all
395 396 def [](arg)
396 397 case arg
397 398 when String
398   - ZONES_MAP[arg]
  399 + ZONES_MAP[arg] ||= lookup(arg)
399 400 when Numeric, ActiveSupport::Duration
400 401 arg *= 3600 if arg.abs <= 13
401 402 all.find { |z| z.utc_offset == arg.to_i }
@@ -409,6 +410,12 @@ def [](arg)
409 410 def us_zones
410 411 US_ZONES
411 412 end
  413 +
  414 + private
  415 +
  416 + def lookup(name)
  417 + (tzinfo = find_tzinfo(name)) && create(tzinfo.name.freeze)
  418 + end
412 419 end
413 420 end
414 421 end
8 activesupport/test/time_zone_test.rb
@@ -73,6 +73,14 @@ def test_now_enforces_fall_dst_rules
73 73 end
74 74 end
75 75
  76 + def test_unknown_timezones_delegation_to_tzinfo
  77 + zone = ActiveSupport::TimeZone['America/Montevideo']
  78 + assert_equal ActiveSupport::TimeZone, zone.class
  79 + assert_equal zone.object_id, ActiveSupport::TimeZone['America/Montevideo'].object_id
  80 + assert_equal Time.utc(2010, 1, 31, 22), zone.utc_to_local(Time.utc(2010, 2)) # daylight saving offset -0200
  81 + assert_equal Time.utc(2010, 3, 31, 21), zone.utc_to_local(Time.utc(2010, 4)) # standard offset -0300
  82 + end
  83 +
76 84 def test_today
77 85 Time.stubs(:now).returns(Time.utc(2000, 1, 1, 4, 59, 59)) # 1 sec before midnight Jan 1 EST
78 86 assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today

0 comments on commit 2c148cd

Please sign in to comment.
Something went wrong with that request. Please try again.