class MoneyHeuristics::SearchTree

Attributes

currency_data[R]

Public Class Methods

new(currency_data) click to toggle source
# File lib/money-heuristics/search_tree.rb, line 3
def initialize(currency_data)
  @currency_data = currency_data
end

Public Instance Methods

build() click to toggle source

Build a search tree from the currency database

# File lib/money-heuristics/search_tree.rb, line 8
def build
  {
    by_symbol:   currencies_by_symbol,
    by_iso_code: currencies_by_iso_code,
    by_name:     currencies_by_name
  }
end

Private Instance Methods

currencies_by_iso_code() click to toggle source
# File lib/money-heuristics/search_tree.rb, line 36
def currencies_by_iso_code
  {}.tap do |result|
    currency_data.each do |_, currency|
      (result[currency[:iso_code].downcase] ||= []) << currency
    end
  end
end
currencies_by_name() click to toggle source
# File lib/money-heuristics/search_tree.rb, line 44
def currencies_by_name
  {}.tap do |result|
    currency_data.each do |_, currency|
      name_parts = currency[:name].unaccent.downcase.split
      name_parts.each {|part| part.chomp!('.')}

      # construct one branch per word
      root = result
      while name_part = name_parts.shift
        root = (root[name_part] ||= {})
      end

      # the leaf is a currency
      (root[:value] ||= []) << currency
    end
  end
end
currencies_by_symbol() click to toggle source
# File lib/money-heuristics/search_tree.rb, line 20
def currencies_by_symbol
  {}.tap do |result|
    currency_data.each do |_, currency|
      symbol = (currency[:symbol]||"").downcase
      symbol.chomp!('.')
      (result[symbol] ||= []) << currency

      (currency[:alternate_symbols] || []).each do |ac|
        ac = ac.downcase
        ac.chomp!('.')
        (result[ac] ||= []) << currency
      end
    end
  end
end