Class: Unitwise::Expression::Decomposer

Inherits:
Object
  • Object
show all
Defined in:
lib/unitwise/expression/decomposer.rb

Overview

The decomposer is used to turn string expressions into collections of terms. It is responsible for executing the parsing and transformation of a string, as well as caching the results.

Constant Summary collapse

MODES =
[:primary_code, :secondary_code, :names, :slugs, :symbol]
PARSERS =
MODES.reduce({}) do |hash, mode|
  hash[mode] = Parser.new(mode); hash
end
TRANSFORMER =
Transformer.new

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(expression) ⇒ Decomposer

Returns a new instance of Decomposer.



18
19
20
21
22
23
# File 'lib/unitwise/expression/decomposer.rb', line 18

def initialize(expression)
  @expression = expression.to_s
  if terms.nil? || terms.empty?
    fail ExpressionError, "Could not evaluate '#{@expression}'."
  end
end

Instance Attribute Details

#expressionObject (readonly)

Returns the value of attribute expression.



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

def expression
  @expression
end

#modeObject (readonly)

Returns the value of attribute mode.



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

def mode
  @mode
end

Instance Method Details

#parseObject



25
26
27
28
29
30
31
# File 'lib/unitwise/expression/decomposer.rb', line 25

def parse
  @parse ||= PARSERS.reduce(nil) do |_, (mode, parser)|
    parsed = parser.parse(expression) rescue next
    @mode = mode
    break parsed
  end
end

#termsObject



37
38
39
40
41
42
43
# File 'lib/unitwise/expression/decomposer.rb', line 37

def terms
  @terms ||= if transform.respond_to?(:terms)
    transform.terms
  else
    Array(transform)
  end
end

#transformObject



33
34
35
# File 'lib/unitwise/expression/decomposer.rb', line 33

def transform
  @transform ||= TRANSFORMER.apply(parse, :mode => mode)
end