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?
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
You can maybe have a look at this gem, which let's you perform some unit conversions.
Quantity on Github
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With