From 022d9f7ce6d1237c4103a2aed561220e1c0f4dcc Mon Sep 17 00:00:00 2001 From: Geoff Buesing Date: Wed, 23 Jan 2008 01:56:22 +0000 Subject: Introduce ActiveSupport::TimeWithZone, for wrapping Time instances with a TimeZone. Introduce instance methods to Time for creating TimeWithZone instances, and class methods for managing a global time zone git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@8696 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- activesupport/CHANGELOG | 2 + activesupport/lib/active_support.rb | 2 + .../lib/active_support/core_ext/date_time.rb | 2 + activesupport/lib/active_support/core_ext/time.rb | 2 + .../lib/active_support/core_ext/time/zones.rb | 68 +++++++ activesupport/lib/active_support/time_with_zone.rb | 156 +++++++++++++++ activesupport/test/core_ext/time_with_zone_test.rb | 212 +++++++++++++++++++++ 7 files changed, 444 insertions(+) create mode 100644 activesupport/lib/active_support/core_ext/time/zones.rb create mode 100644 activesupport/lib/active_support/time_with_zone.rb create mode 100644 activesupport/test/core_ext/time_with_zone_test.rb (limited to 'activesupport') diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index 53ae421131..fa3e94dbf2 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,5 +1,7 @@ *SVN* +* Introduce ActiveSupport::TimeWithZone, for wrapping Time instances with a TimeZone. Introduce instance methods to Time for creating TimeWithZone instances, and class methods for managing a global time zone. [Geoff Buesing] + * Replace non-dst-aware TimeZone class with dst-aware class from tzinfo_timezone plugin. TimeZone#adjust and #unadjust are no longer available; tzinfo gem must now be present in order to perform time zone calculations, via #local_to_utc and #utc_to_local methods. [Geoff Buesing] * Extract ActiveSupport::Callbacks from Active Record, test case setup and teardown, and ActionController::Dispatcher. #10727 [Josh Peek] diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb index 7a0476b729..4d2f873a8d 100644 --- a/activesupport/lib/active_support.rb +++ b/activesupport/lib/active_support.rb @@ -50,3 +50,5 @@ require 'active_support/json' require 'active_support/multibyte' require 'active_support/base64' + +require 'active_support/time_with_zone' diff --git a/activesupport/lib/active_support/core_ext/date_time.rb b/activesupport/lib/active_support/core_ext/date_time.rb index 1d711de70b..66a93eac43 100644 --- a/activesupport/lib/active_support/core_ext/date_time.rb +++ b/activesupport/lib/active_support/core_ext/date_time.rb @@ -1,10 +1,12 @@ require 'date' require 'active_support/core_ext/time/behavior' +require 'active_support/core_ext/time/zones' require 'active_support/core_ext/date_time/calculations' require 'active_support/core_ext/date_time/conversions' class DateTime include ActiveSupport::CoreExtensions::Time::Behavior + include ActiveSupport::CoreExtensions::Time::Zones include ActiveSupport::CoreExtensions::DateTime::Calculations include ActiveSupport::CoreExtensions::DateTime::Conversions end diff --git a/activesupport/lib/active_support/core_ext/time.rb b/activesupport/lib/active_support/core_ext/time.rb index d87c4ec65a..ea50511a96 100644 --- a/activesupport/lib/active_support/core_ext/time.rb +++ b/activesupport/lib/active_support/core_ext/time.rb @@ -11,9 +11,11 @@ end require 'active_support/core_ext/time/behavior' require 'active_support/core_ext/time/calculations' require 'active_support/core_ext/time/conversions' +require 'active_support/core_ext/time/zones' class Time#:nodoc: include ActiveSupport::CoreExtensions::Time::Behavior include ActiveSupport::CoreExtensions::Time::Calculations include ActiveSupport::CoreExtensions::Time::Conversions + include ActiveSupport::CoreExtensions::Time::Zones end diff --git a/activesupport/lib/active_support/core_ext/time/zones.rb b/activesupport/lib/active_support/core_ext/time/zones.rb new file mode 100644 index 0000000000..563d522d9a --- /dev/null +++ b/activesupport/lib/active_support/core_ext/time/zones.rb @@ -0,0 +1,68 @@ +module ActiveSupport #:nodoc: + module CoreExtensions #:nodoc: + module Time #:nodoc: + # Methods for creating TimeWithZone objects from Time instances + module Zones + + def self.included(base) #:nodoc: + base.extend(ClassMethods) if base == ::Time # i.e., don't include class methods in DateTime + end + + module ClassMethods + attr_reader :zone + + # Sets a global default time zone, separate from the system time zone in ENV['TZ']. + # Accepts either a Rails TimeZone object, a string that identifies a + # Rails TimeZone object (e.g., "Central Time (US & Canada)"), or a TZInfo::Timezone object + # + # Any Time or DateTime object can use this default time zone, via #in_current_time_zone. + # Example: + # + # Time.zone = 'Hawaii' # => 'Hawaii' + # Time.utc(2000).in_current_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00 + def zone=(zone) + @zone = get_zone(zone) + end + + def zone_reset! + @zone = nil + end + + def get_zone(zone) + ::String === zone || ::Numeric === zone ? TimeZone[zone] : zone + end + end + + # Gives the corresponding time in the supplied zone. self is assumed to be in UTC regardless of constructor. + # + # Examples: + # + # t = Time.utc(2000) # => Sat Jan 01 00:00:00 UTC 2000 + # t.in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00 + # t.in_time_zone('Hawaii') # => Fri, 31 Dec 1999 14:00:00 HST -10:00 + def in_time_zone(zone) + ActiveSupport::TimeWithZone.new(self, ::Time.get_zone(zone)) + end + + # Returns the simultaneous time in Time.zone + def in_current_time_zone + in_time_zone(::Time.zone) + end + + # Replaces the existing zone; leaves time value intact. Examples: + # + # t = Time.utc(2000) # => Sat Jan 01 00:00:00 UTC 2000 + # t.change_time_zone('Alaska') # => Sat, 01 Jan 2000 00:00:00 AKST -09:00 + # t.change_time_zone('Hawaii') # => Sat, 01 Jan 2000 00:00:00 HST -10:00 + def change_time_zone(zone) + ActiveSupport::TimeWithZone.new(nil, ::Time.get_zone(zone), self) + end + + # Replaces the existing zone to Time.zone; leaves time value intact + def change_time_zone_to_current + change_time_zone(::Time.zone) + end + end + end + end +end \ No newline at end of file diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb new file mode 100644 index 0000000000..dcd55ae93d --- /dev/null +++ b/activesupport/lib/active_support/time_with_zone.rb @@ -0,0 +1,156 @@ +module ActiveSupport + # A Time-like class that can represent a time in any time zone. Necessary because standard Ruby Time instances are + # limited to UTC and the system's ENV['TZ'] zone + class TimeWithZone + include Comparable + attr_reader :time_zone + + def initialize(utc_time, time_zone = nil, local_time = nil) + @utc = utc_time + @time = local_time + @time_zone = time_zone + end + + # Returns a Time instance that represents the time in time_zone + def time + @time ||= utc? ? @utc : time_zone.utc_to_local(@utc) + end + + # Returns a Time instance that represents the time in UTC + def utc + @utc ||= utc? ? @time : time_zone.local_to_utc(@time) + end + alias_method :comparable_time, :utc + + # Returns the underlying TZInfo::TimezonePeriod for the local time + def period + @period ||= get_period_for_local + end + + # Returns the simultaneous time in the specified zone + def in_time_zone(new_zone) + utc.in_time_zone(new_zone) + end + + # Returns the simultaneous time in Time.zone + def in_current_time_zone + utc.in_current_time_zone + end + + # Changes the time zone without converting the time + def change_time_zone(new_zone) + time.change_time_zone(new_zone) + end + + # Changes the time zone to Time.zone without converting the time + def change_time_zone_to_current + time.change_time_zone_to_current + end + + # Returns a Time.local() instance of the simultaneous time in your system's ENV['TZ'] zone + def localtime + utc.dup.localtime # use #dup because Time#localtime is destructive + end + + def dst? + utc? ? false : period.dst? + end + + # The TimeZone class has no zone for UTC, so this class uses the absence of a time zone to indicate UTC + def utc? + !time_zone + end + + def utc_offset + utc? ? 0 : period.utc_total_offset + end + + def formatted_offset(colon = true, alternate_utc_string = nil) + utc? && alternate_utc_string || utc_offset.to_utc_offset_s(colon) + end + + # Time uses #zone to display the time zone abbreviation, so we're duck-typing it + def zone + utc? ? 'UTC' : period.abbreviation.to_s + end + + def inspect + "#{time.strftime('%a, %d %b %Y %H:%M:%S')} #{zone} #{formatted_offset}" + end + + def xmlschema + "#{time.strftime("%Y-%m-%dT%H:%M:%S")}#{formatted_offset(true, 'Z')}" + end + + def to_json(options = nil) + %("#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}") + end + + # :db format outputs time in UTC; all others output time in local. Uses TimeWithZone's strftime, so %Z and %z work correctly + def to_s(format = :default) + return utc.to_s(format) if format == :db + if formatter = ::Time::DATE_FORMATS[format] + formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter) + else + "#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby 1.9 Time#to_s format + end + end + + # Replaces %Z and %z directives with #zone and #formatted_offset, respectively, before passing to + # Time#strftime, so that zone information is correct + def strftime(format) + format = format.gsub('%Z', zone).gsub('%z', formatted_offset(false)) + time.strftime(format) + end + + # Use the time in UTC for comparisons + def <=>(other) + other = other.comparable_time if other.respond_to?(:comparable_time) # to coerce time from TimeWithZone + utc <=> other + end + + # A TimeProxy acts like a Time, so just return self + def to_time + self + end + + # so that self acts_like?(:time) + def acts_like_time? + true + end + + # Say we're a Time to thwart type checking + def is_a?(klass) + klass == ::Time || super + end + alias_method :kind_of?, :is_a? + + # Neuter freeze because freezing can cause problems with lazy loading of attributes + def freeze + self + end + + # Ensure proxy class responds to all methods that underlying time instance responds to + def respond_to?(sym) + super || time.respond_to?(sym) + end + + # Send the missing method to time instance, and wrap result in a new TimeWithZone with the existing time_zone + def method_missing(sym, *args, &block) + result = time.__send__(sym, *args, &block) + result = result.change_time_zone(time_zone) if result.acts_like?(:time) + result + end + + private + def get_period_for_local + t = time + begin + time_zone.period_for_local(t, true) + rescue ::TZInfo::PeriodNotFound # failover logic from TzTime + t -= 1.hour + retry + end + end + end +end diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb new file mode 100644 index 0000000000..5b0c0fd569 --- /dev/null +++ b/activesupport/test/core_ext/time_with_zone_test.rb @@ -0,0 +1,212 @@ +require 'abstract_unit' + +uses_tzinfo 'TimeWithZoneTest' do + + class TimeWithZoneTest < Test::Unit::TestCase + + def setup + @utc = Time.utc(2000, 1, 1, 0) + @time_zone = TimeZone['Eastern Time (US & Canada)'] + @twz = ActiveSupport::TimeWithZone.new(@utc, @time_zone) + end + + def test_utc + assert_equal @utc, @twz.utc + end + + def test_time + assert_equal Time.utc(1999, 12, 31, 19), @twz.time + end + + def test_time_zone + assert_equal @time_zone, @twz.time_zone + end + + def test_in_time_zone + assert_equal ActiveSupport::TimeWithZone.new(@utc, TimeZone['Alaska']), @twz.in_time_zone('Alaska') + end + + def test_in_current_time_zone + with_time_zone 'Alaska' do + assert_equal ActiveSupport::TimeWithZone.new(@utc, TimeZone['Alaska']), @twz.in_current_time_zone + end + end + + def test_change_time_zone + silence_warnings do # silence warnings raised by tzinfo gem + assert_equal ActiveSupport::TimeWithZone.new(nil, TimeZone['Alaska'], Time.utc(1999, 12, 31, 19)), @twz.change_time_zone('Alaska') + end + end + + def test_change_time_zone_to_current + with_time_zone 'Alaska' do + assert_equal ActiveSupport::TimeWithZone.new(nil, TimeZone['Alaska'], Time.utc(1999, 12, 31, 19)), @twz.change_time_zone_to_current + end + end + + def test_utc? + assert_equal false, @twz.utc? + assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000)).utc? + end + + def test_formatted_offset + assert_equal '-05:00', @twz.formatted_offset + assert_equal '-04:00', ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).formatted_offset #dst + end + + def test_dst? + assert_equal false, @twz.dst? + assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).dst? + end + + def test_zone + assert_equal 'EST', @twz.zone + assert_equal 'EDT', ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).zone #dst + end + + def test_to_json + assert_equal "\"1999/12/31 19:00:00 -0500\"", @twz.to_json + end + + def test_strftime + assert_equal '1999-12-31 19:00:00 EST -0500', @twz.strftime('%Y-%m-%d %H:%M:%S %Z %z') + end + + def test_inspect + assert_equal 'Fri, 31 Dec 1999 19:00:00 EST -05:00', @twz.inspect + end + + def test_to_s + assert_equal '1999-12-31 19:00:00 -0500', @twz.to_s + end + + def test_to_s_db + assert_equal '2000-01-01 00:00:00', @twz.to_s(:db) + end + + def test_xmlschema + assert_equal "1999-12-31T19:00:00-05:00", @twz.xmlschema + end + + def test_compare + assert_equal 1, @twz <=> Time.utc(1999, 12, 31, 23, 59, 59) + assert_equal 0, @twz <=> Time.utc(2000) + assert_equal(-1, @twz <=> Time.utc(2000, 1, 1, 0, 0, 1)) + end + + def test_plus + assert_equal Time.utc(1999, 12, 31, 19, 0 ,5), (@twz + 5).time + end + + def test_plus_with_duration + assert_equal Time.utc(2000, 1, 5, 19, 0 ,0), (@twz + 5.days).time + end + + def test_minus + assert_equal Time.utc(1999, 12, 31, 18, 59 ,55), (@twz - 5).time + end + + def test_minus_with_duration + assert_equal Time.utc(1999, 12, 26, 19, 0 ,0), (@twz - 5.days).time + end + + def test_to_time + assert_equal @twz, @twz.to_time + end + + def test_acts_like_time + assert @twz.acts_like?(:time) + end + + def test_is_a + assert @twz.is_a?(Time) + assert @twz.kind_of?(Time) + assert @twz.is_a?(ActiveSupport::TimeWithZone) + end + + def test_method_missing_with_time_return_value + assert_instance_of ActiveSupport::TimeWithZone, @twz.months_since(1) + assert_equal Time.utc(2000, 1, 31, 19, 0 ,0), @twz.months_since(1).time + end + + def test_method_missing_with_non_time_return_value + assert_equal 1999, @twz.year + assert_equal 12, @twz.month + assert_equal 31, @twz.day + end + + protected + def with_time_zone(zone) + old_zone, Time.zone = Time.zone, Time.get_zone(zone) + yield + ensure + Time.zone = old_zone + end + end + + class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase + def setup + @t, @dt = Time.utc(2000), DateTime.civil(2000) + end + + def test_in_time_zone + silence_warnings do # silence warnings raised by tzinfo gem + with_time_zone 'Eastern Time (US & Canada)' do + assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @t.in_time_zone('Alaska').inspect + assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @dt.in_time_zone('Alaska').inspect + assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @t.in_time_zone('Hawaii').inspect + assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @dt.in_time_zone('Hawaii').inspect + end + end + end + + def test_in_current_time_zone + with_time_zone 'Alaska' do + assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @t.in_current_time_zone.inspect + assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @dt.in_current_time_zone.inspect + end + with_time_zone 'Hawaii' do + assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @t.in_current_time_zone.inspect + assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @dt.in_current_time_zone.inspect + end + with_time_zone nil do + assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @t.in_current_time_zone.inspect + assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @dt.in_current_time_zone.inspect + end + end + + def test_change_time_zone + silence_warnings do # silence warnings raised by tzinfo gem + with_time_zone 'Eastern Time (US & Canada)' do + assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @t.change_time_zone('Alaska').inspect + assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @dt.change_time_zone('Alaska').inspect + assert_equal 'Sat, 01 Jan 2000 00:00:00 HST -10:00', @t.change_time_zone('Hawaii').inspect + assert_equal 'Sat, 01 Jan 2000 00:00:00 HST -10:00', @dt.change_time_zone('Hawaii').inspect + end + end + end + + def test_change_time_zone_to_current + with_time_zone 'Alaska' do + assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @t.change_time_zone_to_current.inspect + assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @dt.change_time_zone_to_current.inspect + end + with_time_zone 'Hawaii' do + assert_equal 'Sat, 01 Jan 2000 00:00:00 HST -10:00', @t.change_time_zone_to_current.inspect + assert_equal 'Sat, 01 Jan 2000 00:00:00 HST -10:00', @dt.change_time_zone_to_current.inspect + end + with_time_zone nil do + assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @t.change_time_zone_to_current.inspect + assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @dt.change_time_zone_to_current.inspect + end + end + + protected + def with_time_zone(zone) + old_zone, Time.zone = Time.zone, Time.get_zone(zone) + yield + ensure + Time.zone = old_zone + end + end +end -- cgit v1.2.3