Are there any solutions for unit conversion in Rails?

I would like to use unit settings in a Ruby on Rails application.

For example, the user should be able to choose between displaying distances in miles or kilometers. And, obviously, not only the display, but also the input of values.

I believe that all values ​​should be stored in one global measuring system in order to simplify the calculations.

Are there any solutions for this? Or should I write my own?

+7
units-of-measurement ruby ruby-on-rails internationalization localization
source share
4 answers

Ruby gemstones β€œruby units” can help:

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 
+11
source share

Perhaps you can take a look at this stone, which allows you to perform some unit conversions.

Quantity on Github

+3
source share

I built Unitwise to solve most of the problems of converting units and measurements to Ruby.

Simple use is as follows:

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

If you want to save measurements in Rails models, you can do something like this:

 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> 
+1
source share

A quick search on GitHub showed this: http://github.com/collectiveidea/measurement

It looks like it is doing what you need (as for conversion between units), but I cannot say that I used it myself.

Edit: Pierre gem looks more robust and active.

0
source share

All Articles