Search code examples
rubysinatrarackthin

Sinatra app executes during load instead of after run method issued


This is a stripped down example of a real app I am building. When I execute my app, this is the result I get. You'll notice that it says that it is running before it is starting. You'll also notice it never says running after the start is issued.

bundle exec rackup
Using thin;
Sapp::App running.
Starting Sapp::App
== Sinatra (v1.4.7) has taken the stage on 4567 for development with backup from Thin
Thin web server (v1.7.0 codename Dunder Mifflin)
Maximum connections set to 1024
Listening on localhost:4567, CTRL+C to stop

My config.ru is:

# http://www.rubydoc.info/gems/webmachine/Webmachine/Adapters/Rack
$started = false
require 'thin'
require 'sinatra'
set :server, (ENV['RACK_ENV'] == 'production' || ENV['RACK_ENV'] == 'staging' ? 'rack' : 'thin')
puts "Using #{settings.server};"
load 'webmachine/adapters/rack.rb'
load File.join(File.dirname(__FILE__), 'sapp.rb')
$started = true
puts 'Starting Sapp::App'
#Sapp::App.run!
Sinatra::Application.run!

I am setting $started just to try to fix this problem, but it doesn't help. My app is executed before it is set. I could control that but, and this is the rub, it does not execute after the run is issued.

sapp.rb is:

ENV['RACK_ENV'] ||= 'development'
Bundler.setup
$: << File.expand_path('../', __FILE__)
$: << File.expand_path('../lib', __FILE__)
require 'dotenv'
Dotenv.load(
    File.expand_path("../.env.#{ENV['RACK_ENV']}", __FILE__),
    File.expand_path("../.env", __FILE__))
module Sapp
  class App < Sinatra::Application
    puts 'Sapp::App has been started.' if $started
    puts 'Sapp::App running.'

  end
end

In the end, if nothing else, Once it says "Starting Sapp::App", it should also say "Sapp::App has been started." and "Sapp::App running."

For the record, both these options do the same thing:

Sapp::App.run!
Sinatra::Application.run!

Solution

  • Okay, I get it. I put the code in a class, but not it a method. Load or require both run open code like this. I need to wrap it in methods, and execute the methods, to do what I want to do.

    Sinatra examples, which I followed, don't make this clear and simply avoid the topic. Many are so simple it doesn't make a difference, and some are just coded within the config.ru. I am coming from Rails and, while I knew this from Rails, it didn't make much of a difference since the vast majority of the code already exists in methods.