Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter version of Dir[File.join(File.dirname(__FILE__), "subdirectory/**/*.rb")]?

Tags:

ruby

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.

like image 375
d11wtq Avatar asked Oct 22 '11 03:10

d11wtq


1 Answers

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)

like image 129
knut Avatar answered Nov 15 '22 04:11

knut