Ruby Cheap Tricks – Monkeypatching unit conversion
A little something I cooked up, inspired by Rails’ ActiveSupport Numeric::Bytes and friends.
Ruby
-
class Numeric
-
-
def grams
-
self
-
end
-
-
alias :gram :grams
-
alias :g :grams
-
-
def kilograms
-
self * 1000.grams
-
end
-
-
alias :kilogram :kilograms
-
alias :kg :kilograms
-
-
def tonne
-
self * 1000.kilograms
-
end
-
-
alias :tonnes :tonne
-
-
def pounds
-
self * 453.59237.grams
-
end
-
-
alias :pound :pounds
-
alias :lb :pounds
-
alias :lbs :pounds
-
-
def stone
-
self * 14.pounds
-
end
-
-
def ton
-
self * 2240.pounds
-
end
-
alias :tons :ton
-
-
def method_missing(method_id, *arguments)
-
if match = /^to_([a-zA-Z]w*)$/.match(method_id.to_s)
-
self / (1.0 * 1.send(match[1]))
-
else
-
super
-
end
-
end
-
end
Being that we use the metric system in AU, I reduce all units to their respective value in grams.
Ruby
-
10.kilograms
-
# => 10000
-
1.lb
-
# => 453.59237
And here’s the payoff: the method_missing override lets you do neat conversion tricks like:
Ruby
-
1.kg.to_lbs
-
# => 2.20462262184878
-
0.3.tonne.to_kg
-
# => 300.0
(There is one caveat, I currently don’t check for the existence of the method given in match[1], so it’s not exactly prime time code just yet…)
January 17th, 2009 at 5:55 pm
I know this post is old, but it was one of the better solutions for what I was looking for a while back. I ended up expanding upon the idea quite a bit, so if you ever need a more complete library, I have a gem available at:
http://github.com/farski/systeme/tree/master