【问题标题】:Units of measurement conversion gem计量单位转换宝石
【发布时间】:2011-09-13 10:14:17
【问题描述】:

对于我的 Rails 项目,我正在寻找一个可以转换质量、体积和其他单位的库。

我需要将千克转换为克,将升转换为汤匙等。

我想,应该是这样的:

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
)

这样的宝石真的存在吗?

谢谢。

【问题讨论】:

    标签: ruby-on-rails-3 gem ruby-on-rails-plugins units-of-measurement


    【解决方案1】:

    你可能想试试ruby-units:

    您可以查看unit definitions 看看这个是否适合您!

    【讨论】:

      【解决方案2】:

      您可以使用Unitwise 执行此操作。它专为大量科学单位的单位转换和测量数学而设计。它不了解 Rails,但连接起来应该相当容易:

      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>
      

      【讨论】:

      • 不错的宝石。感谢您分享在 Rails 的 ActiveRecord 模型中的使用情况。
      • @Josh 如果我的用户可以在输入音量时选择测量类型,我需要如何更改该 volume= 方法?感谢您的帮助!
      • @MicFin,我在这里写了更多关于这个主题的文章:joshwlewis.com/essays/rails-unit-measurement-persistence
      猜你喜欢
      • 2014-11-18
      • 1970-01-01
      • 2011-02-06
      • 2011-11-26
      • 2013-09-20
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多