jo1o3o
jo1o3o

Reputation: 61

Prevent a Ruby script from running

Whenever I load a ruby class file in a different ruby file, it executes the class file being imported. This class file currently instantiates and calls the methods, outside the class definition. Is there a way to prevent the imported file from executing? This happens when I run unit tests too. I tried the following:

load 'file.rb'
require_relative 'file'
require "./file.rb"

Thank you.

Here's what I have in the class file (that I'm trying to import):

class Nim
   #some stuff
end

nim = Nim.new(Player.new)
nim.start_game
nim.configBoard

Upvotes: 1

Views: 286

Answers (1)

ptierno
ptierno

Reputation: 10074

You can change your file too look like the following:

class Nim
  # some stuff
end

if __FILE__ == $0
  nim = Nim.new(Player.new)
  nim.start_game
  nim.configBoard
end

This will only execute those method calls if the file is ran as a script rather than loaded as a library.

Upvotes: 6

Related Questions