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
···
--
Posted via http://www.ruby-forum.com/.
and by File.dirname(__FILE__) + '\somefile.rb', what I meant was:
File.join(File.dirname(__FILE__), 'some_file.rb')
···
--
Posted via http://www.ruby-forum.com/.
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?
···
On Feb 11, 9:51 am, Brandon Lawler <grayswan...@gmail.com> wrote:
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.
Karl von Laudermann wrote:
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:
------------------
$: << File.dirname(__FILE__) unless $:.include? File.dirname(__FILE__)
require 'somefile.rb'
------------------
It will successfully load.
--
Posted via http://www.ruby-forum.com/\.