joshwlewis/unitwise — pull request #11 by steveg-h (2014-06-14 22:15:28+00:00)
Title: Rails integration

Hi Josh,
ok - so here is the basis of a rails I18n integration into Unitwise. The idea is that you can use the I18n to define local units to use with various properties. You define the mapping of atom properties to local units in the yaml eg

:uk
:unitwise
length : m
:us
:unitwise
length : ft

Now you can do unit translations via a units new #localize method which will do conversions on the fly.

steve@steve-laptop:~/git/Unitwise/lib$ irb
2.0.0-p195 :001 > require 'active_record'; $: << '.'; require './unitwise' => true
2.0.0-p195 :002 > a=Unitwise(10,'l/h')
=> #
2.0.0-p195 :003 > a.localize
=> #
2.0.0-p195 :004 > I18n.backend.send(:translations)[:us]={:number=>{:precision=>2, :separator=>".", :delimiter=>",", :significance=>true, :strip_insignificant_zeros=>false}, :unitwise=>{:energy=>"kilowatt.hour", :power=>"kilowatt", :voltage=>"v", :current=>"A", :"fluid volume"=>"[gal_us]", :"flow rate"=>"[gal_us]/h", :frequency=>"Hertz", :temperature=>"Farrenheit", :time=>"s"}}
=> {:number=>{:precision=>2, :separator=>".", :delimiter=>",", :significance=>true, :strip_insignificant_zeros=>false}, :unitwise=>{:energy=>"kilowatt.hour", :power=>"kilowatt", :voltage=>"v", :current=>"A", :"fluid volume"=>"[gal_us]", :"flow rate"=>"[gal_us]/h", :frequency=>"Hertz", :temperature=>"Farrenheit", :time=>"s"}}
2.0.0-p195 :005 > I18n.locale=:us
=> :us
2.0.0-p195 :006 > a.localize
=> #

So, a couple of caveats and todos still:

1. I have some integration into ActiveRecord - an extension of ActiveRecord, but I'm not quite sure where it would be best placed: a new file? This has two elements
- Converting fields into Unitwise objects on load
- working out what units to convert into, which has to be done on a per table basis - but I use a convention over configuration approach, looking for elements in the field names
2. One slight pain at the moment is that you need to have at least one element in the Atom db with a property you are looking for (eg liter/hour defined as a flow rate - as I have done) in order to be able to pick up a key that the I18n can use. It would be helpful if one could work out an extra (Rails) location for unit files - maybe it should also try and load unit .yaml files from Rails.root/config/unitwise ?

Thoughts?

Kind regards

Steve