Search code examples
rubywindowseclipserequirerelative-path

Ruby require_relative executing script?


I'm working on a game server in ruby, and during testing I'm having trouble testing components individually. I wasn't getting output from my launcher, just the server, so I commented out the initialisation of the server- yet eclipse still showed output from the server!

I then went to the command line, assuming eclipse was looking at the wrong file (git has messed it around before, but as you can see, the stack trace shows that Server.rb is being executed in its entirety from line 5: require_relative 'Server':

Sublime/cmd screenshot

This is the text content of the file:

class Launcher


  puts "File saved at #{File.mtime($0)}"


  require_relative 'Server'
  require_relative 'Game'

  #STDOUT.sync = true

  puts "Launcher started"
  #server = Server.new
  print "server made"
  game = Game.new
  #serverThread = Thread.new{server.start()}
  gameThread = Thread.new{game.start()}

  while (running)
    print "Stop? "
    input = gets.chomp
    if (input.equals?("yes"))
      running = false
    end
  end

  server.stop
  game.stop
  gameThread.join
  serverThread.join

end

and the terminal output:

C:\Users\gossfunkel\git\citadelserver\RubyCitadelServer>ruby Launcher.rb
File saved at 2013-06-22 18:16:44 +0100
Server starting up at 2013-06-22 18:16:47 +0100...
C:/Users/gossfunkel/git/citadelserver/RubyCitadelServer/Server.rb:20:in `recvfro
m': Interrupt
        from C:/Users/gossfunkel/git/citadelserver/RubyCitadelServer/Server.rb:2
0:in `run'
        from C:/Users/gossfunkel/git/citadelserver/RubyCitadelServer/Server.rb:1
5:in `start'
        from C:/Users/gossfunkel/git/citadelserver/RubyCitadelServer/Server.rb:3
0:in `<class:Server>'
        from C:/Users/gossfunkel/git/citadelserver/RubyCitadelServer/Server.rb:1
:in `<top (required)>'
        from Launcher.rb:5:in `require_relative'
        from Launcher.rb:5:in `<class:Launcher>'
        from Launcher.rb:1:in `<main>'

How do I require a file without this happening, and should it be?


Solution

  • I can't tell without seeing the classes, but I would guess that either

    • game.start is doing more than you thought, and is starting the server for itself

    • You are, as your subject line suggests, running a different file from the one you are editing (or not saving the file once it is changed). Check by putting an obvious puts at the top of the program. Something like

      puts "File saved at #{File.mtime($0)}"
      

      should do the trick

    • After discussion, it seems there's a third option. The code in Server.pm creates and runs a server as well as defining the class. You need to remove the require as well as the lines that use the Server class.