This is a bit of a micro question, but every time I create a gem and need to load all the files under a subdirectory for some sort of reflective purpose (or just a quick and dirty pre-load), I ask myself "surely there has to be a cleaner way?", in reference to this common pattern:
Dir[File.join(File.dirname(__FILE__), "subdirectory/**/*.rb")].each { |f| require f }
The need to call File.dirname
on __FILE__
that makes it needlessly verbose. You can't really use a relative path inside a gem, since you have no idea where you're being loaded from.
Which rube do you use? With ruby 1.9 you can use require_relative
.
require_relative 'subdirectory/file1.rb'
require_relative 'subdirectory/file2.rb'
#...
But you must know the files. require_relative
will not work with all files in subdirectory. But I would not recommend to use such a generic read in a gem. You should know what you load.
If you really want it, you may use something like this:
Dir.chdir(File.dirname(__FILE__)){
Dir["**/*.rb"].each { |f|
require_relative f
}
}
With ruby 1.8 this should work:
Dir.chdir(File.dirname(__FILE__)){
Dir["./**/*.rb"].each { |f|
require f
}
}
Regarding File.join does some stuff for Windows: File.join builds the Path, so the OS may use it. In unix the path separator is /
, in windows \
. But as you already wrote: ruby understands /
, so it doesn't matter in windows. But what happens if you work with Classic Mac OS? There it is a :
(see Wikipedia Path_(computing)). So it is better to use join, (or you use my Dir.chdir variant)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With