Andrew
Andrew

Reputation: 7883

Sinatra seemingly expecting that class should be a part of current framework

I'm using Sinatra, and have this code for the setup:

require 'sinatra/base'

class MyServer < Sinatra::Base
  def initialize()
    puts 'initialize'
    super(app)

    @my_thing = Something.new
  end

  run! if app_file == $0
end

class Something
  def initialize
    @a_thing
  end
end

When I run ruby test.rb, I get this error:

Unexpected error while processing request: uninitialized constant MyServer::Something

That suggests that it's expecting Something to be a class within MyServer's domain (I only started Ruby recently so don't know the correct terms). Moving the Something class to inside MyServer class, it works.

This is fine for a class written inside this file, but I want to add a class from a relative file as the property. I've tried moving the require_relative statement to inside the class, but that hasn't worked.

Is there a way I can tell it this isn't a part of the current framework, or another way that I should be handling the situation?

Upvotes: 0

Views: 32

Answers (1)

matt
matt

Reputation: 79733

When you call run!, the server is started immediately, and the rest of the script is only evaluated when the server is finished. At the point you call run! in your script the Something class hasn’t been defined yet, so isn’t available to the server.

That line doesn’t necessarily need to be inside the MyServer class, you can move it to the end of the file, but you will need to specify the receivers:

require 'sinatra/base'

class MyServer < Sinatra::Base
  # Define your app...
end

# Your helper object...
class Something
  #...
end

# Now start the server as the last thing:
MyServer.run! if MyServer.app_file == $0

Sinatra itself uses an at_exit block to start the server in classic mode, so that the server is only started after everything has been loaded.

Upvotes: 2

Related Questions