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.
Create your own module/library which you include into scope when you need it to perform this task.
Such as "requre 'unitCoversions' "
And Chances are, somebody has already done this if you look hard enough :)
However DONT try modifying the native core class, that will only end in Misery.
( Also, the class you want to extend is 'numeric' , that will apply to both Integers and Floats :) )
Not entirely clear why I shouldn't do this... Rails does this to the string class to great success.
Because it can be done doesn't mean it should be done. 'Monkey Patching' as it is known can have all sorts of odd side effects, and they can be an epic failure when done wrong.
Do it when there is no good alternative.
Because if you really wanted to do something daft, you could build an entire framework that ALL it did was monkey patch the core classes.
Just for example, flip databasing on its head.
5.getArtist();
10.getEvent();
100.getTrack();
etc etc. there is no limit to how many bad ways there are to do that.
"Bob".createUser();
misery in a cup.
If you want to do something practical, have a Convert class or function,
convert( 3 , { :from=>:miles, :to=>:meters });
at least you're not polluting the global namespace and core functions that way and it makes more coherent sense.