Z
Zev Blut
Hello,
My colleagues and I just encountered an interesting gotcha with
"require".
Put the following in a file called "req1.rb"
-------------- [req1.rb]
#!/usr/local/bin/ruby1.8 -w
puts "$0 #{$0}"
base = $0.split("/")
PATH = base[0...(base.size - 1)].join("/")
def jump
require "req2"
end
puts "Fun"
if __FILE__ == $0
puts "Require 1"
jump
end
---------- [req1.rb]
And then put the following in another file called "req2.rb"
---------- [req2.rb]
require "#{PATH}/req1"
puts "Require 2"
---------- [req2.rb]
Now run req1.rb from the full path.
Here is an example of my output:
========
$ /home/zev/projects/rubyplay/recurse_require/req1.rb
$0 /home/zev/projects/rubyplay/recurse_require/req1.rb
Fun
Require 1
$0 /home/zev/projects/rubyplay/recurse_require/req1.rb
/home/zev/projects/rubyplay/recurse_require/req1.rb:5: warning:
already initialized constant PATH
/home/zev/projects/rubyplay/recurse_require/req1.rb:7: warning: method
redefined; discarding old jump
Fun
Require 1
Require 2
=========
Notice that the __FILE__ == $0 gets called twice!
Also the fact that PATH and jump get redefined too...
Is there a way to easily stop this?
Thanks,
Zev
My colleagues and I just encountered an interesting gotcha with
"require".
Put the following in a file called "req1.rb"
-------------- [req1.rb]
#!/usr/local/bin/ruby1.8 -w
puts "$0 #{$0}"
base = $0.split("/")
PATH = base[0...(base.size - 1)].join("/")
def jump
require "req2"
end
puts "Fun"
if __FILE__ == $0
puts "Require 1"
jump
end
---------- [req1.rb]
And then put the following in another file called "req2.rb"
---------- [req2.rb]
require "#{PATH}/req1"
puts "Require 2"
---------- [req2.rb]
Now run req1.rb from the full path.
Here is an example of my output:
========
$ /home/zev/projects/rubyplay/recurse_require/req1.rb
$0 /home/zev/projects/rubyplay/recurse_require/req1.rb
Fun
Require 1
$0 /home/zev/projects/rubyplay/recurse_require/req1.rb
/home/zev/projects/rubyplay/recurse_require/req1.rb:5: warning:
already initialized constant PATH
/home/zev/projects/rubyplay/recurse_require/req1.rb:7: warning: method
redefined; discarding old jump
Fun
Require 1
Require 2
=========
Notice that the __FILE__ == $0 gets called twice!
Also the fact that PATH and jump get redefined too...
Is there a way to easily stop this?
Thanks,
Zev