Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any solutions for translating measurement units on Rails?

I'd like to implement measurement unit preferences in a Ruby on Rails app.

For instance, the user should be able to select between displaying distances in miles or in kilometers. And, obviously, not only displaying, but entering values, too.

I suppose all values should be stored in one global measurement system to simplify calculations.

Are there any drop-in solutions for this? Or should I maybe write my own?

like image 253
Leonid Shevtsov Avatar asked Jun 09 '10 19:06

Leonid Shevtsov


3 Answers

The ruby gem "ruby-units" may 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
like image 137
Justin L. Avatar answered Nov 02 '22 00:11

Justin L.


You can maybe have a look at this gem, which let's you perform some unit conversions.

Quantity on Github

like image 35
Pierre Avatar answered Nov 02 '22 00:11

Pierre


I built Unitwise to solve most unit conversion and measurement math problems in Ruby.

Simple usage looks like this:

require 'unitwise/ext'

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

If you want store measurements in your Rails models, you could 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>
like image 2
Josh W Lewis Avatar answered Nov 02 '22 02:11

Josh W Lewis