Skip to content
This repository
Browse code

Make 1.months and friends accurate by introducing a Duration class. #…

…6835 [eventualbuddha]

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@5940 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
commit 276c9f29cde80fafa23814b0039f67504255e0fd 1 parent 51d840e
Michael Koziarski authored January 15, 2007
2  activesupport/CHANGELOG
... ...
@@ -1,5 +1,7 @@
1 1
 *SVN*
2 2
 
  3
+* Make 1.months and friends accurate by introducing a Duration class.  #6835 [eventualbuddha]
  4
+
3 5
 * Document Inflector.ordinalize and merge docs from String inflections.  #7023 [smeade]
4 6
 
5 7
 * Unbundle flexmock.  [Jeremy Kemper]
1  activesupport/lib/active_support.rb
@@ -38,6 +38,7 @@
38 38
 require 'active_support/option_merger'
39 39
 
40 40
 require 'active_support/values/time_zone'
  41
+require 'active_support/duration'
41 42
 
42 43
 require 'active_support/json'
43 44
 
2  activesupport/lib/active_support/core_ext/date.rb
... ...
@@ -1,6 +1,8 @@
1 1
 require 'date'
  2
+require File.dirname(__FILE__) + '/date/calculations'
2 3
 require File.dirname(__FILE__) + '/date/conversions'
3 4
 
4 5
 class Date#:nodoc:
  6
+  include ActiveSupport::CoreExtensions::Date::Calculations
5 7
   include ActiveSupport::CoreExtensions::Date::Conversions
6 8
 end
41  activesupport/lib/active_support/core_ext/date/calculations.rb
... ...
@@ -0,0 +1,41 @@
  1
+module ActiveSupport #:nodoc:
  2
+  module CoreExtensions #:nodoc:
  3
+    module Date #:nodoc:
  4
+      # Enables the use of time calculations within Time itself
  5
+      module Calculations
  6
+        def self.included(base) #:nodoc:
  7
+          base.send(:include, ClassMethods)
  8
+          
  9
+          base.send(:alias_method, :plus_without_duration, :+)
  10
+          base.send(:alias_method, :+, :plus_with_duration)
  11
+          
  12
+          base.send(:alias_method, :minus_without_duration, :-)
  13
+          base.send(:alias_method, :-, :minus_with_duration)
  14
+        end
  15
+
  16
+        module ClassMethods
  17
+          def plus_with_duration(other) #:nodoc:
  18
+            if ActiveSupport::Duration === other
  19
+              other.since(self)
  20
+            else
  21
+              plus_without_duration(other)
  22
+            end
  23
+          end
  24
+          
  25
+          def minus_with_duration(other) #:nodoc:
  26
+            self.plus_with_duration(-other)
  27
+          end
  28
+          
  29
+          # Provides precise Date calculations for years, months, and days.  The +options+ parameter takes a hash with 
  30
+          # any of these keys: :months, :days, :years.
  31
+          def advance(options)
  32
+            d = ::Date.new(year + (options.delete(:years) || 0), month, day)
  33
+            d = d >> options.delete(:months) if options[:months]
  34
+            d = d + options.delete(:days) if options[:days]
  35
+            d
  36
+          end
  37
+        end
  38
+      end
  39
+    end
  40
+  end
  41
+end
41  activesupport/lib/active_support/core_ext/numeric/time.rb
@@ -3,51 +3,70 @@ module CoreExtensions #:nodoc:
3 3
     module Numeric #:nodoc:
4 4
       # Enables the use of time calculations and declarations, like 45.minutes + 2.hours + 4.years.
5 5
       #
6  
-      # If you need precise date calculations that doesn't just treat months as 30 days, then have
7  
-      # a look at Time#advance.
  6
+      # These methods use Time#advance for precise date calculations when using from_now, ago, etc. 
  7
+      # as well as adding or subtracting their results from a Time object. For example:
  8
+      #
  9
+      #   # equivalent to Time.now.advance(:months => 1)
  10
+      #   1.month.from_now
  11
+      #
  12
+      #   # equivalent to Time.now.advance(:years => 2)
  13
+      #   2.years.from_now
  14
+      #
  15
+      #   # equivalent to Time.now.advance(:months => 4, :years => 5)
  16
+      #   (4.months + 5.years).from_now
8 17
       # 
9  
-      # Some of these methods are approximations, Ruby's core 
  18
+      # While these methods provide precise calculation when used as in the examples above, care
  19
+      # should be taken to note that this is not true if the result of `months', `years', etc is
  20
+      # converted before use:
  21
+      #
  22
+      #   # equivalent to 30.days.to_i.from_now
  23
+      #   1.month.to_i.from_now
  24
+      #
  25
+      #   # equivalent to 365.25.days.to_f.from_now
  26
+      #   1.year.to_f.from_now
  27
+      #
  28
+      # In such cases, Ruby's core 
10 29
       # Date[http://stdlib.rubyonrails.org/libdoc/date/rdoc/index.html] and 
11 30
       # Time[http://stdlib.rubyonrails.org/libdoc/time/rdoc/index.html] should be used for precision
12 31
       # date and time arithmetic
13 32
       module Time
14 33
         def seconds
15  
-          self
  34
+          ActiveSupport::Duration.new(self, [[:seconds, self]])
16 35
         end
17 36
         alias :second :seconds
18 37
 
19 38
         def minutes
20  
-          self * 60
  39
+          ActiveSupport::Duration.new(self * 60, [[:seconds, self * 60]])
21 40
         end
22 41
         alias :minute :minutes  
23 42
         
24 43
         def hours
25  
-          self * 60.minutes
  44
+          ActiveSupport::Duration.new(self * 3600, [[:seconds, self * 3600]])
26 45
         end
27 46
         alias :hour :hours
28 47
         
29 48
         def days
30  
-          self * 24.hours
  49
+          ActiveSupport::Duration.new(self * 24.hours, [[:days, self]])
31 50
         end
32 51
         alias :day :days
33 52
 
34 53
         def weeks
35  
-          self * 7.days
  54
+          ActiveSupport::Duration.new(self * 7.days, [[:days, self * 7]])
36 55
         end
37 56
         alias :week :weeks
38 57
         
39 58
         def fortnights
40  
-          self * 2.weeks
  59
+          ActiveSupport::Duration.new(self * 2.weeks, [[:days, self * 14]])
41 60
         end
42 61
         alias :fortnight :fortnights
43 62
         
44 63
         def months
45  
-          self * 30.days
  64
+          ActiveSupport::Duration.new(self * 30.days, [[:months, self]])
46 65
         end
47 66
         alias :month :months
48 67
 
49 68
         def years
50  
-          (self * 365.25.days).to_i
  69
+          ActiveSupport::Duration.new(self * 365.25.days, [[:years, self]])
51 70
         end
52 71
         alias :year :years
53 72
 
21  activesupport/lib/active_support/core_ext/time/calculations.rb
@@ -5,6 +5,11 @@ module Time #:nodoc:
5 5
       module Calculations
6 6
         def self.included(base) #:nodoc:
7 7
           base.extend(ClassMethods)
  8
+          
  9
+          base.send(:alias_method, :plus_without_duration, :+)
  10
+          base.send(:alias_method, :+, :plus_with_duration)
  11
+          base.send(:alias_method, :minus_without_duration, :-)
  12
+          base.send(:alias_method, :-, :minus_with_duration)
8 13
         end
9 14
 
10 15
         module ClassMethods
@@ -190,6 +195,22 @@ def yesterday
190 195
         def tomorrow
191 196
           self.since(1.day)
192 197
         end
  198
+        
  199
+        def plus_with_duration(other) #:nodoc:
  200
+          if ActiveSupport::Duration === other
  201
+            other.since(self)
  202
+          else
  203
+            plus_without_duration(other)
  204
+          end
  205
+        end
  206
+
  207
+        def minus_with_duration(other) #:nodoc:
  208
+          if ActiveSupport::Duration === other
  209
+            other.until(self)
  210
+          else
  211
+            minus_without_duration(other)
  212
+          end
  213
+        end
193 214
       end
194 215
     end
195 216
   end
88  activesupport/lib/active_support/duration.rb
... ...
@@ -0,0 +1,88 @@
  1
+module ActiveSupport
  2
+  # Provides accurate date and time measurements using Date#advance and 
  3
+  # Time#advance, respectively. It mainly supports the methods on Numeric,
  4
+  # such as in this example:
  5
+  #
  6
+  #   1.month.ago       # equivalent to Time.now.advance(:months => -1)
  7
+  class Duration < Builder::BlankSlate
  8
+    attr_accessor :value, :parts
  9
+    
  10
+    def initialize(value, parts) #:nodoc:
  11
+      @value, @parts = value, parts
  12
+    end
  13
+    
  14
+    # Adds another Duration or a Numeric to this Duration. Numeric values
  15
+    # are treated as seconds.
  16
+    def +(other)
  17
+      if Duration === other
  18
+        Duration.new(value + other.value, @parts + other.parts)
  19
+      else
  20
+        Duration.new(value + other, @parts + [[:seconds, other]])
  21
+      end
  22
+    end
  23
+    
  24
+    # Subtracts another Duration or a Numeric from this Duration. Numeric
  25
+    # values are treated as seconds.
  26
+    def -(other)
  27
+      self + (-other)
  28
+    end
  29
+    
  30
+    def -@ #:nodoc:
  31
+      Duration.new(-value, parts.map { |type,number| [type, -number] })
  32
+    end
  33
+    
  34
+    def is_a?(klass) #:nodoc:
  35
+      klass == Duration || super
  36
+    end
  37
+    
  38
+    def self.===(other) #:nodoc:
  39
+      other.is_a?(Duration) rescue super
  40
+    end
  41
+    
  42
+    # Calculates a new Time or Date that is as far in the future
  43
+    # as this Duration represents.
  44
+    def since(time = ::Time.now)
  45
+      sum(1, time)
  46
+    end
  47
+    alias :from_now :since
  48
+    
  49
+    # Calculates a new Time or Date that is as far in the past
  50
+    # as this Duration represents.
  51
+    def ago(time = ::Time.now)
  52
+      sum(-1, time)
  53
+    end
  54
+    alias :until :ago
  55
+    
  56
+    def inspect #:nodoc:
  57
+      consolidated = parts.inject(Hash.new(0)) { |h,part| h[part.first] += part.last; h }
  58
+      [:years, :months, :days, :hours, :minutes, :seconds].map do |length|
  59
+        n = consolidated[length]
  60
+        "#{n} #{n == 1 ? length.to_s.singularize : length.to_s}" if n.nonzero?
  61
+      end.compact.to_sentence
  62
+    end
  63
+    
  64
+    protected
  65
+    
  66
+    def sum(sign, time = ::Time.now) #:nodoc:
  67
+      parts.inject(time) do |t,(type,number)|
  68
+        case t
  69
+        when ::Time
  70
+          if type == :seconds
  71
+            t + (sign * number)
  72
+          else
  73
+            t.advance(type => sign * number)
  74
+          end
  75
+        when ::Date
  76
+          raise ArgumentError, "Adding seconds to a Date does not make sense" if type == :seconds
  77
+          t.advance(type => sign * number)
  78
+        end
  79
+      end
  80
+    end
  81
+    
  82
+    private
  83
+    
  84
+    def method_missing(method, *args, &block) #:nodoc:
  85
+      value.send(method, *args)
  86
+    end
  87
+  end
  88
+end
13  activesupport/test/core_ext/duration_test.rb
... ...
@@ -0,0 +1,13 @@
  1
+require File.dirname(__FILE__) + '/../abstract_unit'
  2
+
  3
+class DurationTest < Test::Unit::TestCase
  4
+  def test_inspect
  5
+    assert_equal '1 month',                         1.month.inspect
  6
+    assert_equal '1 month and 1 day',               (1.month + 1.day).inspect
  7
+    assert_equal '6 months and -2 days',            (6.months - 2.days).inspect
  8
+    assert_equal '10 seconds',                      10.seconds.inspect
  9
+    assert_equal '10 years, 2 months, and 1 day',   (10.years + 2.months + 1.day).inspect
  10
+    assert_equal '7 days',                          1.week.inspect
  11
+    assert_equal '14 days',                         1.fortnight.inspect
  12
+  end
  13
+end
47  activesupport/test/core_ext/numeric_ext_test.rb
@@ -34,6 +34,53 @@ def test_now
34 34
       assert seconds.from_now >= now + seconds
35 35
     end
36 36
   end
  37
+  
  38
+  def test_irregular_durations
  39
+    assert_equal @now.advance(:days => 3000), 3000.days.since(@now)
  40
+    assert_equal @now.advance(:months => 1), 1.month.since(@now)
  41
+    assert_equal @now.advance(:months => -1), 1.month.until(@now)
  42
+    assert_equal @now.advance(:years => 20), 20.years.since(@now)
  43
+  end
  44
+  
  45
+  def test_duration_addition
  46
+    assert_equal @now.advance(:days => 1, :months => 1), (1.day + 1.month).since(@now)
  47
+    assert_equal @now.advance(:days => 7), (1.week + 5.seconds - 5.seconds).since(@now)
  48
+    assert_equal @now.advance(:years => 2), (4.years - 2.years).since(@now)
  49
+  end
  50
+  
  51
+  def test_time_plus_duration
  52
+    assert_equal @now + 8, @now + 8.seconds
  53
+    assert_equal @now + 22.9, @now + 22.9.seconds
  54
+    assert_equal @now.advance(:days => 15), @now + 15.days
  55
+    assert_equal @now.advance(:months => 1), @now + 1.month
  56
+  end
  57
+  
  58
+  def test_chaining_duration_operations
  59
+    assert_equal @now.advance(:days => 2, :months => -3), @now + 2.days - 3.months
  60
+    assert_equal @now.advance(:days => 1, :months => 2), @now + 1.day + 2.months
  61
+  end
  62
+  
  63
+  def test_duration_after_convertion_is_no_longer_accurate
  64
+    assert_equal 30.days.to_i.since(@now), 1.month.to_i.since(@now)
  65
+    assert_equal 365.25.days.to_f.since(@now), 1.year.to_f.since(@now)
  66
+  end
  67
+end
  68
+
  69
+class NumericExtDateTest < Test::Unit::TestCase
  70
+  def setup
  71
+    @today = Date.today
  72
+  end
  73
+
  74
+  def test_date_plus_duration
  75
+    assert_equal @today + 1, @today + 1.day
  76
+    assert_equal @today >> 1, @today + 1.month
  77
+    assert_raises(ArgumentError) { @today + 1.second }
  78
+  end
  79
+  
  80
+  def test_chaining_duration_operations
  81
+    assert_equal @today.advance(:days => 2, :months => -3), @today + 2.days - 3.months
  82
+    assert_equal @today.advance(:days => 1, :months => 2), @today + 1.day + 2.months
  83
+  end
37 84
 end
38 85
 
39 86
 class NumericExtSizeTest < Test::Unit::TestCase

0 notes on commit 276c9f2

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