Class: Dentaku::DateArithmetic

Inherits:
Object
  • Object
show all
Defined in:
lib/dentaku/date_arithmetic.rb

Instance Method Summary collapse

Constructor Details

#initialize(date) ⇒ DateArithmetic

Returns a new instance of DateArithmetic.



3
4
5
# File 'lib/dentaku/date_arithmetic.rb', line 3

def initialize(date)
  @base = date
end

Instance Method Details

#add(duration) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/dentaku/date_arithmetic.rb', line 7

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



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/dentaku/date_arithmetic.rb', line 26

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