Sequel::Units

stability-wip Build Status Gem Version Dependency Status

Sequel plugin for working with numeric values with unit.

Basic usage

Let's say you have a Sequel model Order which has a numeric attribute called quantity with unit (e.g. "10 kg").

Your migration file would look like

DB.create_table(:orders) do
  primary_key :id
  column :quantity_scalar, Integer # "{attribute}_scalar" which stands for the scalar value ("10" in this case).
  column :quantity_unit, String # "{attribute}_unit" which stands for the unit ("kg" in this case).
end

Your model definition then looks like

class Order < Sequel::Model
  plugin :units

  value_with_unit :quantity
end

Now instances of the model Order have an instance method #quantity.

order = Order.new(quantity_scalar: 10, quantity_unit: 'kg')
# => #<Order @values={:quantity_scalar=>10, :quantity_unit=>"kg"}>
order.quantity
# => 10 kg
order.quantity(in_unit: 'gram')
# => 10000 gram

Note order.quantity here is an instance of RubyUnits::Unit, so you can get the original scalar value or the unit by calling methods #scalar or #units. See Ruby Units for more details.

order.quantity.scalar
# => 10
order.quantity.units
# => "kg"

Custom name for scalar and unit

You can specify your own favorite names for scalar and unit.

class Order < Sequel::Model
  plugin :units

  value_with_unit :quantity, scalar: :my_scalar, unit: :my_unit
end

order = Order.new(my_scalar: 10, my_unit: 'kg')
# => #<Order @values={:my_scalar=>10, :my_unit=>"kg"}>
order.quantity
# => 10 kg

Inverse unit

Let's say you have a Sequel model Product. You might want to have price with unit like "5 USD / kg" (price per weight), but want to store the weight unit as "kg" instead of "1/kg", separate from the currency.

class Product < Sequel::Model
  plugin :units

  value_with_unit :price, inverse_unit: :weight_unit
end

product = Product.new(price_scalar: 5, price_unit: 'USD', weight_unit: 'kg')
# => #<Product @values={:price_scalar=>5, :price_unit=>"USD", :weight_unit=>"kg"}>
product.price
# => 5 USD/kg

TODO

  • [ ] Specify attributes of associated models.
  • [ ] Define calculations with multiple attributes using Unit Math