6

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
  • 20,679
  • 5
  • 53
  • 80
joemoe
  • 5,594
  • 8
  • 41
  • 58

3 Answers3

6

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
  • 44,716
  • 18
  • 112
  • 146
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
  • 14,658
  • 12
  • 64
  • 124
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
  • 45,674
  • 14
  • 125
  • 142