auto load

Jared Carroll

One thing I never looked too far into Rails was: what of my files in lib do I need to require in and what don’t I need to require in?

It turns out that if you follow some naming conventions you can avoid require‘ing files in, which can help keep your various environment files shorter.

If you have a class or module in lib who’s name follows the Ruby conventions of MixedCase and who’s file name is the lower case, words separated by underscores pattern, used by your Rails generated files, then it will be require’d automatically.

For example, the following files will be require’d automatically by Rails, there’s no need to require them in any environment file.

In lib/query.rb:

class Query
end

In lib/string_extensions.rb:

module StringExtensions
end

If you want to package your libraries in subdirectories in lib, those too can still be loaded automatically if you follow some conventions. Any directories must correspond to modules and you have to follow the same naming convention mentioned above.

For example, the following file will be require’d automatically by Rails:

In lib/foo/bar.rb:

module Foo

  class Bar
  end

end