Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 
like image 214
Stas Chehovskih Avatar asked Mar 09 '19 00:03

Stas Chehovskih


Video Answer


2 Answers

config.ru (the .ru stands for "rackup") is a Rack configuration file. Rack provides a minimal interface between webservers 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 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 essentially in this config.ru file what's happening is this:

First you require your app code which uses Sinatra's DSL then run the Sinatra framework... so in the context of Sinatra::Application if your app.rb contained something like

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

Which your application will show to you in your browser.

like image 187
emi Avatar answered Sep 21 '22 10:09

emi


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.

like image 40
max Avatar answered Sep 19 '22 10:09

max