Class: Factbase::Assert

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

Overview

The ‘Factbase::Assert` class represents an assertion term in the Factbase system. It verifies that a given condition evaluates to true, raising an error with a specified message if the assertion fails.

Instance Method Summary collapse

Methods included from TermShared

#to_s

Constructor Details

#initialize(operands) ⇒ Assert

Constructor.



14
15
16
17
18
# File 'lib/factbase/terms/assert.rb', line 14

def initialize(operands)
  super()
  @operands = operands
  @op = 'assert'
end

Instance Method Details

#evaluate(fact, maps, fb) ⇒ Boolean

Evaluate term on a fact.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/factbase/terms/assert.rb', line 25

def evaluate(fact, maps, fb)
  assert_args(2)
  message = @operands[0]
  unless message.is_a?(String)
    raise ArgumentError,
          "A string is expected as first argument of 'assert', but '#{message}' provided"
  end
  t = @operands[1]
  unless t.is_a?(Factbase::Term)
    raise ArgumentError,
          "A term is expected as second argument of 'assert', but '#{t}' provided"
  end
  result = t.evaluate(fact, maps, fb)
  # Convert result to boolean-like evaluation
  # Arrays are truthy if they contain at least one truthy element
  truthy =
    if result.is_a?(Array)
      result.any? { |v| v && v != 0 }
    else
      result && result != 0
    end
  raise message unless truthy
  true
end