class Quby::Compiler::Entities::LookupTables

Public Class Methods

from_csv(levels:, compare:, data:) click to toggle source

load csv data into a tree. each row is a path through the tree. String and float types are used to make an exact match. A range is always a range between two floats where the range is between the low value (inclusive) and the high value (exclusive), written as 4:5 (low:high). These boundaries can be given as floats or integers, but internally they are always treated as a floats. The low and high values of a range cannot be equal. Use minfinity or infinity to create infinite ranges.

@params levels [Array<String>] An array of column names @param compare [Array<String>]An array of lookup types (string, float or range) for each column @param data [Array<Array<>>] The rows describing a path through the tree.

# File lib/quby/compiler/entities/lookup_tables.rb, line 32
def self.from_csv(levels:, compare:, data:)
  tree = data.each_with_object({}) do |row, tree|
    add_to_tree(tree, row, levels, compare)
  end
  {levels: levels, tree: tree}
end
new(path) click to toggle source
# File lib/quby/compiler/entities/lookup_tables.rb, line 7
def initialize(path)
  @path = path
end

Private Class Methods

add_to_tree(tree, (value, *path), (level, *levels), (compare, *compares)) click to toggle source
# File lib/quby/compiler/entities/lookup_tables.rb, line 41
def self.add_to_tree(tree, (value, *path), (level, *levels), (compare, *compares))
  key = case compare
        when 'string' then value.to_s
        when 'float' then parse_float(value)
        when 'range' then create_range(value)
        end

  if levels.empty?
    return key
  end

  tree.merge! key => add_to_tree(tree[key] || {}, path, levels, compares)
end
create_range(value) click to toggle source
# File lib/quby/compiler/entities/lookup_tables.rb, line 55
def self.create_range(value)
  min, max = value.split(':').map { |val| parse_float(val) }
  fail 'Cannot create range between two equal values' if min == max
  (min...max)
end
parse_float(value) click to toggle source
# File lib/quby/compiler/entities/lookup_tables.rb, line 61
def self.parse_float(value)
  case value
  when 'infinity'  then Float::INFINITY
  when 'minfinity' then -Float::INFINITY
  else Float(value)
  end
end

Public Instance Methods

fetch(key) click to toggle source
# File lib/quby/compiler/entities/lookup_tables.rb, line 11
def fetch(key)
  csv_path = File.join(@path, "#{key}.csv")
  data = CSV.read(csv_path, col_sep: ';', skip_blanks: true)
  headers = data.shift
  compare = data.shift
  self.class.from_csv(levels: headers, compare: compare, data: data)
end