unitwise-rails is a gem that provides rails extension to the the refined unitwise gem.
Add this line to your application's Gemfile:
gem 'unitwise-rails', github: 'maximebedard/unitwise-rails'# Add the fields :protein_value and :protein_unit when the
# migration is executed.
class AddUnitToIngredients < ActiveRecord::Migration
def self.up
add_unit :ingredients, :protein
end
def self.down
remove_unit :ingredients, :protein
end
end
class CreateIngredients < ActiveRecord::Migration
def change
create_table :ingredients do |t|
t.string :name
t.unit :protein
t.timestamps
end
end
end# Add a method #protein to the model that will always be converted to grams
class Ingredient < ActiveRecord::Base
# Add unit with automatic conversion to grams before save
unit_for :protein, convert_to: :gram
# Add unit with compatibility validation
unit_for :carbohydrate
validates_unit_compatibility_of :carbohydrate, with: :gram
validates_unit_presence_of :carbohydrate
# or
validates_unit :carbohydrate, presence: true, compatibility: :gram
end- Add
unit_forextension to ActiveRecord::Base - Add
unitgeneration to migrations - Add
validates_unitvalidator - Add
validates_unit_compatibility_ofvalidator - Add
validates_unit_presence_ofvalidator - Add
Unitwise::Rails::Migrationtests