Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute code once Sinatra server is running

Tags:

ruby

sinatra

I have a Sinatra Application enclosed in Sinatra::Base and I'd like to run some code once the server has started, how should I go about doing this?

Here's an example:

require 'sinatra'
require 'launchy'

class MyServer < Sinatra::Base
  get '/' do
    "My server"
  end

  # This is the bit I'm not sure how to do
  after_server_running do
    # Launches a browser with this webapp in it upon server start
    Launchy.open("http://#{settings.host}:#{settings.port}/")
  end
end

Any ideas?

like image 998
JP. Avatar asked Apr 07 '10 00:04

JP.


3 Answers

Using the configure block is not the correct way to do this. Whenever you load the file the commands will be run.

Try extending run!

require 'sinatra'
require 'launchy'

class MyServer < Sinatra::Base

  def self.run!
    Launchy.open("http://#{settings.host}:#{settings.port}/")
    super
  end

  get '/' do
    "My server"
  end
end
like image 91
Rafael Oliveira Avatar answered Nov 04 '22 00:11

Rafael Oliveira


This is how I do it; basically running either sinatra or the other code in a separate thread:

require 'sinatra/base'

Thread.new { 
  sleep(1) until MyApp.settings.running?
  p "this code executes after Sinatra server is started"
}
class MyApp < Sinatra::Application
  # ... app code here ...

  # start the server if ruby file executed directly
  run! if app_file == $0
end
like image 28
KKS Avatar answered Nov 04 '22 00:11

KKS


If you're using Rack (which you probably are) I just found out there's a function you can call in config.ru (it's technically an instance method of Rack::Builder) that lets you run a block of code after the server has been started. It's called warmup, and here's the documented usage example:

warmup do |app|
  client = Rack::MockRequest.new(app)
  client.get('/')
end

use SomeMiddleware
run MyApp
like image 2
Hubro Avatar answered Nov 03 '22 23:11

Hubro