class Unitwise::Expression::Decomposer

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.

Constants

MODES

Attributes

expression[R]
mode[R]

Public Class Methods

new(expression) click to toggle source
# File lib/unitwise/expression/decomposer.rb, line 51
def initialize(expression)
  @expression = expression.to_s
  if expression.empty? || terms.nil? || terms.empty?
    fail(ExpressionError, "Could not evaluate '#{ expression }'.")
  end
end
parse(expression) click to toggle source

Parse an expression to an array of terms and cache the results

# File lib/unitwise/expression/decomposer.rb, line 13
def parse(expression)
  expression = expression.to_s
  if cache.key?(expression)
    cache[expression]
  elsif decomposer = new(expression)
    cache[expression] = decomposer
  end
end
parsers() click to toggle source
# File lib/unitwise/expression/decomposer.rb, line 22
def parsers
  @parsers ||= MODES.reduce({}) do |hash, mode|
    hash[mode] = Parser.new(mode); hash
  end
end
transformer() click to toggle source
# File lib/unitwise/expression/decomposer.rb, line 28
def transformer
  @transformer = Transformer.new
end

Private Class Methods

cache() click to toggle source

A simple cache to prevent re-decomposing the same units api private

# File lib/unitwise/expression/decomposer.rb, line 36
def cache
  @cache ||= {}
end
reset() click to toggle source

Reset memoized data. Allows rebuilding of parsers, transformers, and the cache after list of atoms has been modified.

# File lib/unitwise/expression/decomposer.rb, line 42
def reset
  @parsers = nil
  @transformer = nil
  @cache = nil
end

Public Instance Methods

parse() click to toggle source
# File lib/unitwise/expression/decomposer.rb, line 58
def parse
  self.class.parsers.reduce(nil) do |_, (mode, parser)|
    parsed = parser.parse(expression) rescue next
    @mode = mode
    break parsed
  end
end
terms() click to toggle source
# File lib/unitwise/expression/decomposer.rb, line 70
def terms
  @terms ||= if transform.respond_to?(:terms)
    transform.terms
  else
    Array(transform)
  end
end
transform() click to toggle source
# File lib/unitwise/expression/decomposer.rb, line 66
def transform
  @transform ||= self.class.transformer.apply(parse, :mode => mode)
end