8

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.

Christopher Oezbek
  • 23,994
  • 6
  • 61
  • 85
joemoe
  • 5,734
  • 10
  • 43
  • 60

3 Answers3

8

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.

Chowlett
  • 45,935
  • 20
  • 116
  • 150
5
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

SwiftMango
  • 15,092
  • 13
  • 71
  • 136
0

For better readability you can also use $PROGRAM_NAME

  if __FILE__ == $PROGRAM_NAME
      puts "Executed via CLI #{__FILE__}"
    else
      puts 'Referred'
    end

More info: What does __FILE__ == $PROGRAM_NAME mean in ruby?

Teoman shipahi
  • 47,454
  • 15
  • 134
  • 158