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 |
# File 'lib/dentaku/date_arithmetic.rb', line 11 def add(duration) case duration when Numeric @base + duration when Dentaku::AST::Duration::Value case @base when Time change_datetime(@base.to_datetime, duration.unit, duration.value).to_time else change_datetime(@base, duration.unit, 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
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/dentaku/date_arithmetic.rb', line 28 def sub(duration) case duration when Date, DateTime, Numeric, Time @base - duration when Dentaku::AST::Duration::Value case @base when Time change_datetime(@base.to_datetime, duration.unit, -duration.value).to_time else change_datetime(@base, duration.unit, -duration.value) end when Dentaku::TokenScanner::DATE_TIME_REGEXP @base - Time.parse(duration).to_datetime else raise Dentaku::ArgumentError.for(:incompatible_type, value: duration, for: Numeric), "'#{duration || duration.class}' is not coercible for date arithmetic" end end |