calculations.rb 1.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
module ActiveSupport #:nodoc:
  module CoreExtensions #:nodoc:
    module Date #:nodoc:
      # Enables the use of time calculations within Time itself
      module Calculations
        def self.included(base) #:nodoc:
          base.send(:include, ClassMethods)
          
          base.send(:alias_method, :plus_without_duration, :+)
          base.send(:alias_method, :+, :plus_with_duration)
          
          base.send(:alias_method, :minus_without_duration, :-)
          base.send(:alias_method, :-, :minus_with_duration)
        end

        module ClassMethods
          def plus_with_duration(other) #:nodoc:
            if ActiveSupport::Duration === other
              other.since(self)
            else
              plus_without_duration(other)
            end
          end
          
          def minus_with_duration(other) #:nodoc:
            self.plus_with_duration(-other)
          end
          
          # Provides precise Date calculations for years, months, and days.  The +options+ parameter takes a hash with 
          # any of these keys: :months, :days, :years.
          def advance(options)
            d = ::Date.new(year + (options.delete(:years) || 0), month, day)
            d = d >> options.delete(:months) if options[:months]
            d = d + options.delete(:days) if options[:days]
            d
          end
        end
      end
    end
  end
end