GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS

Written by thoughtbot

auto load

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.

lib/query.rb


class Query
end

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: lib/foo/bar.rb


module Foo

class Bar end

end