Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a Ruby program was executed or imported via require

How do you check if a Ruby file was imported via "require" or "load" and not simply executed from the command line?

For example:

Contents of foo.rb:

puts "Hello"

Contents of bar.rb

require 'foo'

Output:

$ ./foo.rb
Hello
$ ./bar.rb
Hello

Basically, I'd like calling bar.rb to not execute the puts call.

like image 970
joemoe Avatar asked Apr 26 '12 13:04

joemoe


2 Answers

Change foo.rb to read:

if __FILE__ == $0
  puts "Hello"
end

That checks __FILE__ - the name of the current ruby file - against $0 - the name of the script which is running.

like image 87
Chowlett Avatar answered Oct 02 '22 15:10

Chowlett


if __FILE__ != $0       #if the file is not the main script which is running
  quit                  #then quit
end

Put this on top of all code in foo.rb

like image 45
SwiftMango Avatar answered Oct 02 '22 16:10

SwiftMango