Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Units of measurement conversion gem

for my Rails project, I'm looking for a library, that can convert mass, volume and other units.

I need to convert kilogramms to gramms, liters to tablespoons etc.

I think, it should look like this:

class Product < ActiveRecord:Base
  acts_as_physical_unit, :volume, :mass, :count
end

class Ingredient < ActiveRecord:Base
  acts_as_physical_unit, :volume, :mass, :count
end

olive_oil = Product.new(:name => "Olive Oil", :volume => "1000 ml")

caesar_salad = Recipe.new(:name => "Caesar salad",
  :ingredients => [
    Ingredient.new(:product => [olive_oil], :volume => "5 tablespoons")
  ]

# In ingredients of "Caesar Salad" are 5 tablespoons of "Olive Oil" specified.
# We should create "Caesar Salad" for 50 persons.
# How mutch bottles of "Olive Oil" should be ordered ?
order = OrderItem.new(
  :product => olive_oil,
  :count => olive_oil.count_for(caesar_salad.ingredients.first)) * 50
)

Does such a gem even exists ?

Thanks.

like image 734
AntonAL Avatar asked Jun 12 '11 14:06

AntonAL


2 Answers

You might want to try ruby-units:

You can check the unit definitions to see if this one suits you !

like image 92
ybart Avatar answered Oct 24 '22 10:10

ybart


You could do this with Unitwise. It's designed for unit conversion and measurement math for a ton of scientific units. It has no knowledge of Rails, but it should be fairly easy to wire up:

require 'unitwise/ext'

class Ingredient < ActiveRecord::Base
  # store the value as milliliter in the database
  def volume=(amount)
    super(amount.convert_to('ml').to_f)
  end

  # convert the value to a measurement when retrieved
  def volume
    super().convert_to('ml')
  end
end

# Now you can initialize by sending a number (assumed to be in ml)
cooking_wine = Ingredient.new(name: 'Cooking Wine', volume: 750)

# Or send any other volume measurement
olive_oil = Ingredient.new(name: 'Olive Oil', volume: 1.liter)
cumin = Ingredient.new(name: 'Cumin', volume: 5.teaspoon)

# Now volume returns a measurement
cooking_wine.volume # => #<Unitwise::Measurement 750.0 ml>

# And the volume can be converted to whatever you want.
olive_oil.volume.convert_to('gallon') # => #<Unitwise::Measurement 0.21996924829908776 gallon>

# Use .to_f to get just the numeric value
cumin.volume.convert_to('cup').to_f # => 0.10416666666666666

# You can perform whatever math you need on the volumes as well:
2.0 * (olive_oil.volume + cooking_wine.volume) => #<Unitwise::Measurement 3500.0 ml>
like image 37
Josh W Lewis Avatar answered Oct 24 '22 11:10

Josh W Lewis