From: Gavin Kistner Date: 2004-10-19T11:32:59+09:00 Subject: Re: Relative #require On Oct 18, 2004, at 8:32 AM, trans. (T. Onoma) wrote: > module Kernel > # Require files from same dir as running script. > def import(*args) > fd = File.dirname(caller[0]) > args.each do |file_name| > require File.join(fd, file_name) > end > end > end Thanks for passing this along, although it doesn't work. caller[0] is neither a path, nor the path to the 'current' file. (The one I supplied is even worse, as __FILE__ doesn't change at all.) From my test (below), caller[2] seems like it would be usable (with some regexp massaging) but that feels like a hack which will break under some odd circumstance. Perhaps someone more clever than I can figure out a clean, robust way to do this. ~/Desktop/tmp.rb ~/Desktop/libs/lib1.rb ~/Desktop/libs/lib2.rb ~/Desktop/libs/sublib/lib3.rb % cat tmp.rb module Kernel require 'pathname' def import( *paths ) paths.each{ |path| puts path,caller.join("\n"),' ' } end end import 'Go find "./libs/lib1.rb" given "libs/lib1.rb"' require 'libs/lib1.rb' % cat libs/lib1.rb 1.times{ import 'Go find "./libs/lib2.rb" given "lib2.rb"' require 'libs/lib2.rb' } % cat libs/lib2.rb class Bar class Jim import 'Go find "./libs/sublib/lib3.rb" given "sublib/lib3.rb"' require 'libs/sublib/lib3.rb' end end % cat libs/sublibs/libs3.rb import 'Go find "./libs/sublib/lib4.rb given "lib4.rb"' % ruby tmp.rb Go find "./libs/lib1.rb" given "libs/lib1.rb" /Users/gavinkistner/Desktop/tmp.rb:6:in `each' /Users/gavinkistner/Desktop/tmp.rb:6:in `import' /Users/gavinkistner/Desktop/tmp.rb:12 Go find "./libs/lib2.rb" given "lib2.rb" /Users/gavinkistner/Desktop/tmp.rb:6:in `each' /Users/gavinkistner/Desktop/tmp.rb:6:in `import' ./libs/lib1.rb:4 ./libs/lib1.rb:3:in `times' ./libs/lib1.rb:3 /Users/gavinkistner/Desktop/tmp.rb:13:in `require' /Users/gavinkistner/Desktop/tmp.rb:13 Go find "./libs/sublib/lib3.rb" given "sublib/lib3.rb" /Users/gavinkistner/Desktop/tmp.rb:6:in `each' /Users/gavinkistner/Desktop/tmp.rb:6:in `import' ./libs/lib2.rb:3 ./libs/lib1.rb:5:in `require' ./libs/lib1.rb:5 ./libs/lib1.rb:3:in `times' ./libs/lib1.rb:3 /Users/gavinkistner/Desktop/tmp.rb:13:in `require' /Users/gavinkistner/Desktop/tmp.rb:13 Go find "./libs/sublib/lib4.rb given "lib4.rb" /Users/gavinkistner/Desktop/tmp.rb:6:in `each' /Users/gavinkistner/Desktop/tmp.rb:6:in `import' ./libs/sublib/lib3.rb:1 ./libs/lib2.rb:4:in `require' ./libs/lib2.rb:4 ./libs/lib1.rb:5:in `require' ./libs/lib1.rb:5 ./libs/lib1.rb:3:in `times' ./libs/lib1.rb:3 /Users/gavinkistner/Desktop/tmp.rb:13:in `require' /Users/gavinkistner/Desktop/tmp.rb:13