Where is the best place to add a method to the integer class in Rails?
I\'d like to add a to_meters
and to_miles
methods.
Realize the question is old, but I think the clearest way would be to make a Distance class with two attributes @length
and @unit
.
You'd just need a conversion hash, probably as a class variable of Distance:
class Distance
@@conversion_rates = {
meters: {
feet: 3.28084,
meters: 1.0
}
}
def to(new_unit)
new_length = @length * @@conversion_rates[@unit][new_unit]
Distance.new( new_length, new_unit )
end
end
And it would look kinda like:
Distance.new(3, :meters).to(:feet)
which i honestly think looks better than
3.meters.to_feet