class Metamorphosis::Engine

Attributes

registry[R]

Public Class Methods

new() click to toggle source
# File lib/metamorphosis/engine.rb, line 15
def initialize
  reset!
end

Public Instance Methods

common_unit_category(source, dest) click to toggle source
# File lib/metamorphosis/engine.rb, line 24
def common_unit_category(source, dest)
  source_categories = @registry.unit_categories(source)
  dest_categories   = @registry.unit_categories(dest)

  category = (source_categories & dest_categories).first
end
convert_to(dest_unit_name, source) click to toggle source
# File lib/metamorphosis/engine.rb, line 31
def convert_to(dest_unit_name, source)
  return source if dest_unit_name.to_sym == source.unit_symbol

  exponent, dest_unit_symbol = @parser.parse(dest_unit_name)
  return unless @registry.include?(dest_unit_symbol)

  category = common_unit_category(source.unit_symbol, dest_unit_symbol)
  unless category
    raise IncompatibleUnitsError,
      "Cannot convert from #{source.unit_symbol} to #{dest_unit_symbol}"
  end

  value = to_base_value(category, source)

  from_base_value(category, dest_unit_symbol, value, exponent)
end
from_base_value(category, dest_unit_symbol, value, exponent) click to toggle source
# File lib/metamorphosis/engine.rb, line 48
def from_base_value(category, dest_unit_symbol, value, exponent)
  conversion_factor = @registry.conversion_factor(category, dest_unit_symbol)
  if conversion_factor.is_a?(Array)
    new_unit_value = conversion_factor[1].call(value)
  else
    new_unit_value = value / (exponent * conversion_factor)
  end
  UnitValue.new(dest_unit_symbol, new_unit_value)
end
numeric_to_unit_value(numeric, unit_name) click to toggle source
# File lib/metamorphosis/engine.rb, line 9
def numeric_to_unit_value(numeric, unit_name)
  exponent, unit_symbol = @parser.parse(unit_name)
  return nil unless @registry.include?(unit_symbol)
  UnitValue.new(unit_symbol, numeric, exponent)
end
register_unit(category, symbols, value) click to toggle source
# File lib/metamorphosis/engine.rb, line 67
def register_unit(category, symbols, value)
  value = value.is_a?(UnitValue) ? to_base_value(category, value) : value
  symbols = Array(symbols)
  symbols.each do |unit_symbol|
    @registry.register(category, unit_symbol, value)
  end
end
reset!() click to toggle source
# File lib/metamorphosis/engine.rb, line 19
def reset!
  @registry = UnitRegistry.new
  @parser = PrefixParser.new(DEFAULT_PREFIXES, @registry)
end
to_base_value(category, source_unit) click to toggle source
# File lib/metamorphosis/engine.rb, line 58
def to_base_value(category, source_unit)
  conversion_factor = @registry.conversion_factor(category, source_unit.unit_symbol)
  if(conversion_factor.is_a?(Array))
    conversion_factor[0].call(source_unit.value) * source_unit.exponent
  else
    source_unit.to_f * conversion_factor
  end
end