Class: PortableExpressions::Expression

Inherits:
Object
  • Object
show all
Includes:
Serializable
Defined in:
lib/portable_expressions/expression.rb

Overview

An expression represents 2 or more ‘operands` that are reduced using a defined `operator`. The `operands` of an `Expression` can be `Scalars`, `Variables`, or other `Expressions`. All `operands` must respond to the symbol (i.e. support the method) defined by the `Expression#operator`.

Constant Summary collapse

ALLOWED_OPERANDS =
[
  Expression,
  Scalar,
  Variable
].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Serializable

#to_json

Constructor Details

#initialize(operator, *operands, output: nil) ⇒ Expression

Returns a new instance of Expression.

Parameters:

  • operator (String, Symbol)

    Mathematical operator to ‘reduce` the `operands` array with.

  • *operands (Variable, Expressions)

    2 or more Variables, Scalars, or Expressions

  • output (String) (defaults to: nil)

    The variable to write the expressions output to



22
23
24
25
26
27
28
# File 'lib/portable_expressions/expression.rb', line 22

def initialize(operator, *operands, output: nil)
  @operator = operator.to_sym
  @operands = operands
  @output = output

  validate!
end

Instance Attribute Details

#operandsObject (readonly)

Returns the value of attribute operands.



16
17
18
# File 'lib/portable_expressions/expression.rb', line 16

def operands
  @operands
end

#operatorObject (readonly)

Returns the value of attribute operator.



16
17
18
# File 'lib/portable_expressions/expression.rb', line 16

def operator
  @operator
end

#outputObject

Sometimes you may want to conditionally set an ‘output` after initialization.



17
18
19
# File 'lib/portable_expressions/expression.rb', line 17

def output
  @output
end

Instance Method Details

#as_jsonObject



35
36
37
38
39
40
41
# File 'lib/portable_expressions/expression.rb', line 35

def as_json
  super.merge(
    operator: operator.to_s,
    operands: operands.map(&:as_json),
    output: output
  )
end

#to_sObject

TODO(@omkarmoghe): This string representation might not make the most sense for non-math expressions.



31
32
33
# File 'lib/portable_expressions/expression.rb', line 31

def to_s
  "(#{operands.join(" #{operator} ")})"
end