Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a Ruby script detect that it is running in irb?

Tags:

ruby

irb

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?

like image 496
ReWrite Avatar asked Feb 09 '10 05:02

ReWrite


1 Answers

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> 
like image 103
Wayne Conrad Avatar answered Nov 14 '22 20:11

Wayne Conrad