开发者

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

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜