Sequel::Units

Sequel plugin for working with numeric values with unit.

Basic usage

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

Your migration file would look like

DB.create_table(:products) 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 Product < Sequel::Model
  plugin :units

  value_with_unit :quantity
end

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

product = Product.new(quantity_scalar: 10, quantity_unit: 'kg')
# => #<Product @values={:quantity_scalar=>10, :quantity_unit=>"kg"}>
quantity = product.quantity
# => 10 kg

Note product.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.

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