Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I write Ruby code that is executed only when my script is run, but not when it is required?

Tags:

ruby

I want to write a Ruby script something like this:

class Foo
  # instance methods here

  def self.run
    foo = Foo.new
    # do stuff here
  end
end

# This code should only be executed when run as a script, but not when required into another file
unless required_in?  # <-- not a real Kernel method
  Foo.run
end
# ------------------------------------------------------------------------------------------

I want to be able to unit test it, which is why I don't want the code outside of the class to run unless I execute the script directly, i.e. ruby foo_it_up.rb.

I know I can simply put the Foo class in another file and require 'foo' in my script. In fact, that is probably a better way to do it, just in case Foo's functionality is needed somewhere else. So my question is more academic than anything, but I'd still be interested in knowing how to do this in Ruby.

like image 261
Josh Glover Avatar asked Jun 23 '11 07:06

Josh Glover


1 Answers

This is usually done with

if __FILE__ == $0
  Foo.run
end

but I prefer

if File.identical?(__FILE__, $0)
  Foo.run
end

because programs like ruby-prof can make $0 not equal __FILE__ even when you use --replace-progname.

$0 refers to the name of the program ($PROGRAM_NAME), while __FILE__ is the name of the current source file.

like image 180
Andrew Grimm Avatar answered Sep 17 '22 17:09

Andrew Grimm