Question

I have a Ruby script that defines a class. I would like the script to execute the statement

BoolParser.generate :file_base=>'bool_parser'

only when the script is invoked as an executable, not when it is require'd from irb (or passed on the command line via -r). What can I wrap around the statement above to prevent it from executing whenever my Ruby file is loaded?

Was it helpful?

Solution

The condition $0 == __FILE__ ...

!/usr/bin/ruby1.8

class BoolParser

  def self.generate(args)
    p ['BoolParser.generate', args]
  end

end

if $0 == __FILE__
  BoolParser.generate(:file_base=>__FILE__)
end

... is true when the script is run from the command line...

$ /tmp/foo.rb
["BoolParser.generate", {:file_base=>"/tmp/foo.rb"}]

... but false when the file is required or loaded by another ruby script.

$ irb1.8
irb(main):001:0> require '/tmp/foo'
=> true
irb(main):002:0> 

OTHER TIPS

use $0

in irb the value of $0 is "irb"

in your file is "/path/to/file"

an explanation here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top