ExUc - Elixir Unit Converter
Converts values between units.
Installation
From Hex, the package can be installed as:
-
Add
ex_ucto your list of dependencies inmix.exs:
```elixir
def deps do
[{:ex_uc, "~> 0.1.0"}]
end
```-
Ensure
ex_ucis started before your application:
```elixir
def application do
[applications: [:ex_uc]]
end
```Usage
The quickest way is the function convert:
iex>ExUc.convert("5 pounds", "oz")
"80.00 oz"This is just a shortcut for the 3-steps pipeline:
import ExUc
new_val = from("5 pounds") # %ExUc.Value{unit: :lb, value: 5, kind: :mass}
|> to(:oz) # %ExUc.Value{unit: :oz, value: 80, kind: :mass}
|> as_string # "80.00 oz"Errors
Only two errors are returned when found, both as self descriptive strings:
"undefined origin": Unit for the original value can't be parsed or found in the configuration."undetermined conversion": Conversion between the given units can't be determined.
Configuration
The only configurable variable is precision, by default 2. It determines how many decimals will have the result when is converted into string.
Adding more units
Every unit supported by ExUc is defined in a config file in config/units/<KIND>.ex, e.g. config/units/temperature.ex.
Each of these files requires to have the following structure:
use Mix.Config
config :ex_uc, :<KIND>_units,
<UNIT>: ["alias 1", "alias 2", "alias N"], # List with every alias intended to relate to unit identified by UNIT
config :ex_uc, :<KIND>_conversions,
<UNIT_A>_to_<UNIT_B>: 0.001, # Multiplication factor
<UNIT_C>_to_<UNIT_D>: &(&1 + 5) # Conversion formula.
<UNIT_X>_to_<UNIT_Y>: :special # Atom referencing a special method. Which have two sections:
- Aliases
-
Key as
<KIND>_unitswhere kind identifies the type of measurement, e.g: length, temperature, pressure, etc. -
Each unit to support in the
kindas a pairunit:aliaseswhere unit is the most used unit and aliases is a list of strings (or a single one), one for each supported representation of the unit.
-
Key as
- Conversions
-
Key as
<KIND_conversions>using the same kind from the alias section. -
Each conversion as a pair
key:conversion, where key is an atom with the pattern<UNIT_FROM>_to_<UNIT_TO>, and conversion could be a number, or a closure, or an atom. Numeric conversions describe multiplication factors, and can be also used as<B>_to_<A>: 1 / conversionfor a<A>_to_<B>: factorwithout explicit definition. When a factor is not enough, a closure can be used as a simple formula. For special cases use an atom to describe a function in moduleSpecial.
-
Key as
Documentation
Detailed documentation can be found at hex docs.
Note
This project was inspired by the awesome Ruby gem by Kevin C. Olbrich, Ph.D.