Permalink
Browse files

TimeZones lazy load

Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
  • Loading branch information...
1 parent 2ff7303 commit d1911a0707eb03758644d600a03c6dcfa14405f0 @spastorino spastorino committed with jeremy Apr 20, 2010
Showing with 9 additions and 24 deletions.
  1. +9 −24 activesupport/lib/active_support/values/time_zone.rb
@@ -190,6 +190,7 @@ def self.seconds_to_utc_offset(seconds, colon = true)
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 @@ def self.seconds_to_utc_offset(seconds, colon = true)
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 @@ def period_for_local(time, dst=true)
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 @@ def new(name)
# 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 @@ def all
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 @@ def [](arg)
# 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

0 comments on commit d1911a0

Please sign in to comment.