Class: Dentaku::DateArithmetic
- Inherits:
-
Object
- Object
- Dentaku::DateArithmetic
- Defined in:
- lib/dentaku/date_arithmetic.rb
Instance Method Summary collapse
- #add(duration) ⇒ Object
-
#initialize(date) ⇒ DateArithmetic
constructor
A new instance of DateArithmetic.
- #sub(duration) ⇒ Object
Constructor Details
#initialize(date) ⇒ DateArithmetic
Returns a new instance of DateArithmetic.
3 4 5 6 7 8 9 |
# File 'lib/dentaku/date_arithmetic.rb', line 3 def initialize(date) if date.respond_to?(:strftime) @base = date else @base = Time.parse(date).to_datetime end end |
Instance Method Details
#add(duration) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/dentaku/date_arithmetic.rb', line 11 def add(duration) case duration when Numeric @base + duration when Dentaku::AST::Duration::Value case duration.unit when :year Time.local(@base.year + duration.value, @base.month, @base.day).to_datetime when :month @base >> duration.value when :day @base + duration.value end else raise Dentaku::ArgumentError.for(:incompatible_type, value: duration, for: Numeric), "'#{duration || duration.class}' is not coercible for date arithmetic" end end |
#sub(duration) ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/dentaku/date_arithmetic.rb', line 30 def sub(duration) case duration when DateTime, Numeric @base - duration when Dentaku::AST::Duration::Value case duration.unit when :year Time.local(@base.year - duration.value, @base.month, @base.day).to_datetime when :month @base << duration.value when :day @base - duration.value end else raise Dentaku::ArgumentError.for(:incompatible_type, value: duration, for: Numeric), "'#{duration || duration.class}' is not coercible for date arithmetic" end end |