From d1911a0707eb03758644d600a03c6dcfa14405f0 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Tue, 20 Apr 2010 18:17:12 -0300 Subject: TimeZones lazy load Signed-off-by: Jeremy Kemper --- .../lib/active_support/values/time_zone.rb | 33 ++++++---------------- 1 file changed, 9 insertions(+), 24 deletions(-) diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb index bc4fb77f9c..2ac5134911 100644 --- a/activesupport/lib/active_support/values/time_zone.rb +++ b/activesupport/lib/active_support/values/time_zone.rb @@ -190,6 +190,7 @@ module ActiveSupport include Comparable attr_reader :name + attr_reader :tzinfo # Create a new TimeZone object with the given name and offset. The # offset is the number of seconds that this time zone is offset from UTC @@ -198,7 +199,7 @@ module ActiveSupport def initialize(name, utc_offset = nil, tzinfo = nil) @name = name @utc_offset = utc_offset - @tzinfo = tzinfo + @tzinfo = tzinfo || TimeZone.find_tzinfo(name) @current_period = nil end @@ -310,32 +311,12 @@ module ActiveSupport tzinfo.period_for_local(time, dst) end - def tzinfo - @tzinfo ||= TimeZone.find_tzinfo(name) - end - # TODO: Preload instead of lazy load for thread safety def self.find_tzinfo(name) require 'tzinfo' unless defined?(::TZInfo) ::TZInfo::TimezoneProxy.new(MAPPING[name] || name) end - unless const_defined?(:ZONES) - ZONES = [] - ZONES_MAP = {} - MAPPING.each_key do |place| - place.freeze - zone = new(place) - ZONES << zone - ZONES_MAP[place] = zone - end - ZONES.sort! - ZONES.freeze - - US_ZONES = ZONES.find_all { |z| z.name =~ /US|Arizona|Indiana|Hawaii|Alaska/ } - US_ZONES.freeze - end - class << self alias_method :create, :new @@ -350,7 +331,11 @@ module ActiveSupport # TimeZone objects per time zone, in many cases, to make it easier # for users to find their own time zone. def all - ZONES + @zones ||= zones_map.values.sort + end + + def zones_map + @zones_map ||= Hash[MAPPING.map { |place, _| [place, create(place)] }] end # Locate a specific time zone object. If the argument is a string, it @@ -361,7 +346,7 @@ module ActiveSupport def [](arg) case arg when String - ZONES_MAP[arg] ||= lookup(arg) + zones_map[arg] ||= lookup(arg) when Numeric, ActiveSupport::Duration arg *= 3600 if arg.abs <= 13 all.find { |z| z.utc_offset == arg.to_i } @@ -373,7 +358,7 @@ module ActiveSupport # A convenience method for returning a collection of TimeZone objects # for time zones in the USA. def us_zones - US_ZONES + @us_zones ||= all.find_all { |z| z.name =~ /US|Arizona|Indiana|Hawaii|Alaska/ } end private -- cgit v1.2.3