6

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.

d11wtq
  • 34,788
  • 19
  • 120
  • 195
  • 2
    interpolate the directory name instead of calling `File.join` – cam Oct 22 '11 at 05:39
  • Heh, I guess that works :) File.join does some stuff for Windows, but given that ruby will load files using `/` regardless, it doesn't really matter. – d11wtq Oct 22 '11 at 05:49
  • See also http://stackoverflow.com/questions/788550/is-there-a-shorter-way-to-require-a-file-in-the-same-directory-in-ruby and http://stackoverflow.com/questions/735073/best-way-to-require-all-files-from-a-directory-in-ruby – knut Oct 22 '11 at 19:40

1 Answers1

1

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)

Noyo
  • 4,874
  • 4
  • 39
  • 41
knut
  • 27,320
  • 6
  • 84
  • 112
  • Great answer. I didn't know about require_relative, thanks! I'm using ruby 1.9 and tbh, not concerned with supporting 1.8 in gems I write... I think supporting old versions of languages just slows down the development of the language in the longer term ;) – d11wtq Oct 22 '11 at 16:05