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.

Parameters:

  • operation (Symbol)

    The arithmetic operation (e.g., :+, :-, :*, :/)

  • operands (Array)

    Operands



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.

Parameters:

Returns:

  • (Object)

    The result of the arithmetic operation

Raises:

  • (ArgumentError)


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 if lefts.nil?
  raise(ArgumentError, 'Too many values at first position, one expected') unless lefts.size == 1
  rights = _values(1, fact, maps, fb)
  return if rights.nil?
  raise(ArgumentError, '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 = Integer(num, 10)
    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(ArgumentError, "Unknown time unit '#{units}' in '#{r}")
      end
  end
  v.__send__(@op, r)
end