Hi --
On Sun, 18 Jun 2006, Jens wrote:
> Hi all,
>
> I''d like to add a instance method to class String.
>
> I should be fairly simple with
>
> class String; def newmethod; do_something ; end; end
>
> and it works perfectly if I test this independently with irb.
> However if I add this to my application.rb I''ll get an error like
>
> (undefined method `newmethod'' for "123456":String)
>
> What''s wrong with that?
If you do this:
class ApplicationController < ActionController::Base
class String
you''re creating a new String class nested inside
ApplicationController. If you want to get into the top-level String
class, you can put the code at the top:
class String
# stuff here
end
class ApplicationController < ActionController::Base
or you can use the path notation to force a top-level constant:
class ::String
Another option is to put the code in a separate file in the lib
subdirectory of your application, and then ''require'' it at
runtime.
That''s probably a cleaner design.
(And don''t forget the many pitfalls of modifying core classes :-)
David
--
David A. Black (dblack@wobblini.net)
Ruby Power and Light, LLC (http://www.rubypowerandlight.com)
See what the readers are saying about "Ruby for Rails"!
http://www.rubypowerandlight.com/quotes