module Converty

Easily convert amounts between different units

Constants

DISTANCE_TYPE
UNITS
VERSION
WEIGHT_TYPE

Public Class Methods

convert(amount, from:, to:) click to toggle source

Convert the specified amount in the from unit to the to the to unit

It does not handle rounding the returned conversion.

Currently supports some distance and weight unit types.

Examples:

Converty.convert(5, from: :km, to: :mi).round(1) => 3.1
Converty.convert(16, from: :oz, to: :lb) => 1.0
# File lib/converty.rb, line 69
def self.convert(amount, from:, to:)
  amount = amount.to_f
  from = from.to_sym
  to = to.to_sym

  to_unit = UNITS[to]
  from_unit = UNITS[from]

  if to_unit.nil? || from_unit.nil?
    invalid_units = []
    invalid_units.push(from) if from_unit.nil?
    invalid_units.push(to) if to_unit.nil?
    raise UnitError.new(invalid_units)
  end

  if to_unit.fetch(:type) != from_unit.fetch(:type)
    raise CantConvertError.new(from, to)
  end

  in_base = from_unit[:base_per] * amount
  in_base / to_unit[:base_per]
end