Adding local files to the ruby path $:

B

Brandon Lawler

Hi; I'm a comp sci undergrad, with decent (maybe 6 months off and on)
Ruby/Rails experience. I'm competent with the syntax and have written a
number of Ruby scripts for various things.

Requiring local files always drove me nuts, due to the need to
explicitly declare the directory in the require statement with require
File.dirname(__FILE__) + '\somefile.rb', which was rather bulky and
inelegant.

I stumbled onto a solution while reading about the array $:. I've hunted
for a solution like this many times, but never found it on Google
anywhere. The solution is this line, affixed to the top of the main
script file:

$: << File.dirname(__FILE__) unless $:.include? File.dirname(__FILE__)

With this, a "require 'somefile.rb'" statement for local files will work
for ANY file linked through all the scripts in the application. My
question is this: why do I not find this method used anywhere? Is there
some staggering disadvantage to doing this that did not occur to me?

Thanks,
Grays
 
B

Brandon Lawler

and by File.dirname(__FILE__) + '\somefile.rb', what I meant was:
File.join(File.dirname(__FILE__), 'some_file.rb')
 
K

Karl von Laudermann

Requiring local files always drove me nuts, due to the need to
explicitly declare the directory in the require statement with require
File.dirname(__FILE__) + '\somefile.rb', which was rather bulky and
inelegant.

I don't understand this; if somefile.rb is in the same directory as
the file that's requiring it, then why do you need the full path? Why
doesn't

require 'somefile.rb'

work by itself?
 
B

Brandon Lawler

Karl said:
I don't understand this; if somefile.rb is in the same directory as
the file that's requiring it, then why do you need the full path? Why
doesn't

Sorry; I forgot to specify that the context I'm discussing is irb. For
hacking at scripts or examples, a lot of times I'll make some variables
global and load the file into irb, then mess with the globals to figure
out how to do whatever I want.

Let's say you have somefile.rb, which can contain anything. Then you
have the file someprog.rb, which contains:
------------------
require 'somefile.rb'
------------------

In irb, if you type:
irb(main):001:0> load 'c:/whatever/someprog.rb'

The prompt will blow up with a "no such file to load" error.

However, if your someprog.rb file contains:
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,979
Messages
2,570,185
Members
46,728
Latest member
FernMcmull

Latest Threads

Top