auto load
Posted by jcarroll
Aug 07
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.
1 2 |
class Query end |
1 2 |
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 berequire‘d automatically by Rails:
lib/foo/bar.rb
1 2 3 4 5 6 |
module Foo class Bar end end |
Comments on this post
Aug 07
Shadowfiend said,
The question is, of course, whether these are automatically required at startup or when the constant is called up via const_missing. I think it’s the latter, but I’m not sure…
Aug 08
Joseph said,
This sub-directory convention pertains to models, controllers and helpers as well. If you want to organise your models directory, you can put them in modules and then move them into sub-directories based on the module name.
I tend not to put models inheriting from ActiveRecord::Base into modules, but it’s useful for distinguishing and grouping non-ActiveRecord classes.
Sorry, comments are closed for this article.
© 2000 - 2009 by thoughtbot, inc.
written by a bushel of tiny robots
Come “ride the toad” on Hoptoad, the app error app.
Thunder Thimble: Brand monitoring for social media.
Widgetfinger: Simple content management for simple websites.
Tee-Bot, funny shirts your friends won't understand!
Umbrella Today: “It’s like totally the simplest weather report ever, Julie.”
Thoughtbot
thoughtbot is a technology consulting firm that provides web application development and design services. We focus on building modern systems, embracing good ideas and delivering elegant solutions.
Interested in learning Rails?
Sign up for our beginning or advanced training.
Archives