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:
6 # 1.month.ago # equivalent to Time.now.advance(:months => -1)
7 class Duration < BasicObject
8 attr_accessor :value, :parts
10 def initialize(value, parts) #:nodoc:
11 @value, @parts = value, parts
14 # Adds another Duration or a Numeric to this Duration. Numeric values
15 # are treated as seconds.
18 Duration.new(value + other.value, @parts + other.parts)
20 Duration.new(value + other, @parts + [[:seconds, other]])
24 # Subtracts another Duration or a Numeric from this Duration. Numeric
25 # values are treated as seconds.
31 Duration.new(-value, parts.map { |type,number| [type, -number] })
34 def is_a?(klass) #:nodoc:
35 klass == Duration || super
38 def self.===(other) #:nodoc:
39 other.is_a?(Duration) rescue super
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)
47 alias :from_now :since
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)
57 consolidated = parts.inject(Hash.new(0)) { |h,part| h[part.first] += part.last; h }
58 [:years, :months, :days, :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
66 def sum(sign, time = ::Time.now) #:nodoc:
67 parts.inject(time) do |t,(type,number)|
68 if t.acts_like?(:time) || t.acts_like?(:date)
70 t.since(sign * number)
72 t.advance(type => sign * number)
75 raise ArgumentError, "expected a time or date, got #{time.inspect}"
82 def method_missing(method, *args, &block) #:nodoc:
83 value.send(method, *args)