41

What is this file config.ru, and what is it for in Sinatra projects? In my lanyard of the project, such code is written:

require './app'
run Sinatra::Application
1
  • 2
    What's a "lanyard"? Did you mean to say "template"?
    – Warren P
    Commented May 13, 2020 at 15:56

3 Answers 3

45

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!'

11

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.

6

config.ru is a default configuration file for a rackup command with a list of instructions for Rack.

Rack is an interface and architecture that provides a domain specific language (DSL) and connects an application with a world of web. In two words, it allows to build web applications and work with requests, responses (and many other web-related technologies) in a most convenient way.

Sinatra as well as Rails are web frameworks, so they both use Rack:

http://recipes.sinatrarb.com/p/middleware

https://guides.rubyonrails.org/rails_on_rack.html

Not the answer you're looking for? Browse other questions tagged or ask your own question.