A gem for dealing with weights in ruby and rails.
Add this line to your application's Gemfile:
gem'weighable'And then execute:
$ bundle
Or install it yourself as:
$ gem install weighable
Using the weight class is as simple as:
weight=Weighable::Weight.new(5,:gram)weight=weight + Weighable::Weight.new(1,:ounce)weight=weight.round(4)This gets even cleaner when you include the core extensions (included by default with rails):
require'weighable/core_ext'weight=5.gramsweight=weight + 1.ounceweight=weight.round(4)By default core extensions are included with rails. You also get some helpers to integrate weight into active record.
Add a weight attribute to a model:
classAddWeightToItem < ActiveRecord::Migrationdefchangechange_table:itemsdo |t|
t.weighable:my_weightend# ORadd_weighable:items,:my_weightendendclassItem < ActiveRecord::BaseincludeWeighable::Modelweighable:my_weight# OR require the field to be presentweighable:my_weight,presence: trueend# Now use ititem=Item.firstitem.weight=6.gramsitem.save!pitem.weight == 6.grams# => trueAfter checking out the repo, run bin/setup to install dependencies. You can also run bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.
Bug reports and pull requests are welcome on GitHub at https://github.com/greenbits/weighable.
The gem is available as open source under the terms of the MIT License.