Class: Factbase::Arithmetic

Inherits:
TermBase show all
Defined in:
lib/factbase/terms/arithmetic.rb

Overview

Factbase::Arithmetic is a class for performing arithmetic operations.

Instance Method Summary collapse

Methods inherited from TermBase

#to_s

Constructor Details

#initialize(operation, operands) ⇒ Arithmetic

Constructor.



13
14
15
16
17
# File 'lib/factbase/terms/arithmetic.rb', line 13

def initialize(operation, operands)
  super()
  @op = operation
  @operands = operands
end

Instance Method Details

#evaluate(fact, maps, fb) ⇒ Object

Evaluate term on a fact.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/factbase/terms/arithmetic.rb', line 24

def evaluate(fact, maps, fb)
  assert_args(2)
  lefts = _values(0, fact, maps, fb)
  return nil if lefts.nil?
  raise 'Too many values at first position, one expected' unless lefts.size == 1
  rights = _values(1, fact, maps, fb)
  return nil if rights.nil?
  raise 'Too many values at second position, one expected' unless rights.size == 1
  v = lefts[0]
  r = rights[0]
  if v.is_a?(Time) && r.is_a?(String)
    (num, units) = r.split
    num = num.to_i
    r =
      case units
      when 'seconds', 'second'
        num
      when 'minutes', 'minute'
        num * 60
      when 'hours', 'hour'
        num * 60 * 60
      when 'days', 'day'
        num * 60 * 60 * 24
      when 'weeks', 'week'
        num * 60 * 60 * 24 * 7
      else
        raise "Unknown time unit '#{units}' in '#{r}"
      end
  end
  v.send(@op, r)
end