Sequel::Units
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
column :quantity_unit, String
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.quantity
order.quantity(in_unit: '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
order.quantity.units
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.quantity
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.price
TODO