代码之家  ›  专栏  ›  技术社区  ›  Leonid Shevtsov

有没有在轨道上转换测量单位的解决方案?

  •  7
  • Leonid Shevtsov  · 技术社区  · 16 年前

    我想在RubyonRails应用程序中实现度量单位首选项。

    例如,用户应该能够在以英里或公里显示距离之间进行选择。显然,不仅要显示,还要输入值。

    我想所有的值都应该存储在一个全局测量系统中,以简化计算。

    这方面的解决方案有没有下降?还是我自己写?

    4 回复  |  直到 11 年前
        1
  •  11
  •   Justin L.    16 年前

    红宝石“红宝石单位”可能有助于:

    http://ruby-units.rubyforge.org/ruby-units/

    require 'rubygems'
    require 'ruby-units'
    
    '8.4 mi'.to('km')      # => 13.3576 km
    '8 lb 8 oz'.to('kg')   # => 3.85554 kg
    
    a = '3 in'.to_unit
    b = Unit('5 cm')
    a + b                  # => 4.968 in
    (a + b).to('cm')       # => 16.62 cm
    
        2
  •  3
  •   user229044    14 年前

    你可以看看这个宝石,让我们来做一些单位转换。

    Quantity 吉瑟布论

        3
  •  1
  •   Josh W Lewis    11 年前

    我建造 Unitwise 解决Ruby中的大多数单位转换和测量数学问题。

    简单用法如下:

    require 'unitwise/ext'
    
    26.2.mile.convert_to('km') 
    # => #<Unitwise::Measurement 42.164897129794255 kilometer>
    

    如果要在Rails模型中存储度量值,可以这样做:

    class Race < ActiveRecord::Base
      # Convert value to kilometer and store the number
      def distance=(value)
        super(value.convert_to("kilometer").to_f)
      end
    
      # Convert the database value to kilometer measurement when retrieved
      def distance
        super.convert_to('kilometer')
      end
    end
    
    # Then you could do
    five_k = Race.new(distance: 5)
    five_k.distance
    # => #<Unitwise::Measurement 5 kilometer>
    
    marathon = Race.new(distance: 26.2.mile)
    marathon.distance.convert_to('foot')
    # => #<Unitwise::Measurement 138336.27667255333 foot>
    
        4
  •  0
  •   Robert Speicher    16 年前

    在Github上快速搜索发现: http://github.com/collectiveidea/measurement

    听起来像是做了你需要的(关于单位之间的转换),但我不能说我自己用过它。

    编辑:皮埃尔的宝石看起来更坚固和活跃。

    推荐文章