3
votes

Say I have some custom classes that don't belong in models, controllers etc, I should put this in /lib correct?

In rails < 3 I would add this directory to my loadpath and in rails 3+ I would add this to my autoload_path. Is this correct?

Now say I have some classes that extends already defined classes. Where should I put this so its run on startup. Forexample say I want to add the method 'foo' on String.

class String
  def foo
    'foo;
  end
end

Where should I put this class so it's defined on startup?

Another weird bug I have is when I try to namespace classes in lib.

module MyProject
 class Foo
 end
end

Now in a console:

ruby-1.9.2-p136 :004 > MyProject::Foo
LoadError: Expected /Users/me/workspace/my_project/lib/foo.rb to define Foo
 from /Users/rob/.rvm/gems/ruby-1.9.2-p136/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:492:in `load_missing_constant'
 from /Users/rob/.rvm/gems/ruby-1.9.2-p136/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:183:in `block in const_missing'

I keep getting this error. How can I load this file?

2

2 Answers

8
votes

In rails 3, the autoload path is disabled in the config/application.rb

#config.autoload_paths += %W(#{config.root}/extras)

You have to de-comment this line if you want to load code from lib dir.

3
votes

You can generally put the class files wherever you want, for example you could put them in app/others and add the directory to your load_path in Rails 2 or autoload_path in Rails 3.

To extend already defined classes you'll probably want to put the files in your config/initializers directory.

To fix the bug you mention you should probably define the Foo class in your foo.rb file, and make sure that the module names match up (Bags and MyProject).

The reason the name was changed to autoload is that the classes in autoload_paths are actually getting autoloaded, not simply loaded. This is the difference between using 'autoload' and 'require' in Ruby.