What is this file config.ru, and what is it for?

config.ru is a Rack configuration file (ru stands for "rackup"). Rack provides a minimal interface between web servers that support Ruby and Ruby frameworks. It's like a Ruby implementation of a CGI which offers a standard protocol for web servers to execute programs.

Rack's run command here means for requests to the server, make Sinatra::Application the execution context from which Sinatra's DSL could be used. All DSL methods on the main are then delegated to this class.

So in this config.ru file, first you require your app code which uses Sinatra's DSL then run the Sinatra framework. In the context of Sinatra::Application if your app.rb contained this:

get '/' do
  'Hello world!'
end

The get block would mean something to Rack, in this case when someone tries to access (GET) the home url, send back 'Hello world!'


Rack provides a minimal interface between webservers that support Ruby and Ruby frameworks.

The interface just assumes that you have an object that responds to a call method (like a proc) and returns a array with:

  • The HTTP response code
  • A Hash of headers
  • The response body, which must respond to each

You can run a basic Rack server with the rackup command which will search for a config.ru file in the current directory.

You can create a minimal hello world server with:

# config.ru
run Proc.new { |env| ['200', {'Content-Type' => 'text/html'}, ['Hello World']] }
# run this with the `rackup` command

Since Sinatra just like Rails builds on Rack it uses rackup internally to interface between the server and the framework. config.ru is thus the entry point to any Rack based program.

What it does is bootstrap the application and pass the Sinatra::Application class to rack which has a call class method.

Sinatra::Application is then responsible for taking the incoming request (the env) and passing it to the routes your application provides and then passing back the response code, headers, and response body.

Tags:

Ruby

Sinatra