Ruby-on-rails – Rails load path questions

ruby-on-rails

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?

Best Answer

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.

Related Topic