Question

If I have a whole bunch of requires in my main app file:

require 'a'
require 'b'
require 'c'
require 'd'
require 'e'
require 'f'
require 'g'
require 'h'
require 'i'
require 'j'

would it be bad practice to put strip all of these requires out and put them in a separate file that just does all of the requires - let's call it 'all_requires.rb' - so then I can just say:

require 'all_requires'

I've never seen this approach in other people's code so perhaps there's a reason?

Was it helpful?

Solution

There's nothing really wrong with it per se, but there just doesn't generally seem to be a lot of benefit to that in Ruby. It hides what the file at hand depends on and just adds another level of indirection. It also doesn't work all that well with conditional requires. It's more common to do like:

DEPENDENCIES = %w(a b c d e f g h i j k)
DEPENDENCIES.each {|f| require f}

That way you avoid the huge train of require lines but still keep it localized and declarative.

OTHER TIPS

The main reason for requiring all files explicitly is just that - it is normally good to be explicit. This way someone else who reads your code (or you, months later) will have an easier time finding out what is going on.

If your requires are in other files, it can become rather difficult to know where things are coming from.

If you commonly require all 10 of those files in multiple files then yes that makes perfect sense.

You are doing one extra file access and parsing one extra file this way but to worry about that is really micro-optimization. If it makes your code cleaner or just more readable then go for it. That's far more important than any perceived saved cycles by not reading one file from disk.

If you use opcode caching (APC, eAccelerator, etc) even the theoretical difference pretty much goes away since you're doing unconditional includes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top