Extending Ruby classes in Rails

Hi.

I’ve placed the following in lib/mods.rb:

class String
def String.foo
“bar”
end

def bar
“baz”
end
end

But it does not get picked up:

white:~/svn/tagticks morten$ script/console
Loading development environment.

String.foo
NoMethodError: undefined method `foo’ for String:Class
from (irb):1

“fdsfs”.foo
NoMethodError: undefined method `foo’ for “fdsfs”:String
from (irb):2

“fdsfs”.bar
NoMethodError: undefined method `bar’ for “fdsfs”:String
from (irb):3

What’s the appropriate way to extend a ruby class for a rails app?

Thanks.

Morten

Morten wrote:

def bar
from (irb):1
Thanks.

Morten


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails

You must require mods somewhere in your rails code. Try adding
require ‘mods’
to your environment.rb, for example. It’s only models and a few other
things that gets loaded automagically.


Ola B. (http://ola-bini.blogspot.com)
JvYAML, RbYAML, JRuby and Jatha contributor
System Developer, Karolinska Institutet (http://www.ki.se)
OLogix Consulting (http://www.ologix.com)

“Yields falsehood when quined” yields falsehood when quined.

What’s the appropriate way to extend a ruby class for a rails app?

You must require mods somewhere in your rails code. Try adding
require ‘mods’
to your environment.rb, for example. It’s only models and a few other
things that gets loaded automagically.

Excellent, I added the following to environment.rb and now it works.

require File.join("#{RAILS_ROOT}/lib", ‘mods’)

Thanks Ola.

Morten

On 7/17/06, Morten [email protected] wrote:

What’s the appropriate way to extend a ruby class for a rails app?

The preferred route that most people take is to bundle the modifications
as
a plugin and require the necessary files in the plugin’s init.rb. See
Top-Funky’s excellent tutorial for more info:
http://nubyonrails.com/articles/2006/05/04/the-complete-guide-to-rails-plugins-part-i

Josh