I am using rails 2.0.2 version and I have a need to add a method to an
existing class and use it in the rails environment. For example, I
would like to add a method to Numeric class, so I coded it as follows
class Numeric
def radians
self * Math::PI/180
end
end
and then placed it under <my rails app>/lib directory. However I am
not able use this new method in my apps controller, ruby throws no
method found error.
the code is ok I think.
but if it's in lib, you would have to require it before you can use it
so if the file is named numeric.rb
then
require "numeric"
either in environment.rb or in the controller or mode where it is used
another option is to put the file in config/initializers
this should be loaded by default (though I haven't used this yet)
If it goes in environment.rb (which is where I put anything that will be
needed anywhere in the application), you'll need to restart your server.
Can't speak about the initializers. Haven't used them yet.
Thanks for the replies. I tried placing the class definition directly
in environment.rb, it works but any updates to
the definition requires server restart.
Probably I'll try placing the .rb file under libs directory and
require statement in controller or directly in the model.
If it goes in environment.rb (which is where I put anything that will be
needed anywhere in the application), you'll need to restart your server.
Can't speak about the initializers. Haven't used them yet.
Oh, I should clarify that I don't mean to put the actual method
definitions in environment.rb. I always put those in a file in lib/.
What I meant was if the require <file> were to go in environment.rb,
then a server restart is required when you change lib/file.