DEV Community

Brittany
Brittany

Posted on

Day 6 : #100DaysofCode - Setting up a Sinatra App : Part 2 - Config.ru

In my last post I mentioned that your Sinatra app file tree should look something like this:

Directory structure:

├── config.ru
├── Gemfile
├── Gemfile.lock
├── Rakefile
├── README
├──── app
│   ├──── controllers
│   │   └──── application_controller.rb
│   ├──── models
│   └──── views
│       ├──── layout.erb
│       └──── index.erb
├──── config
│   ├──── initializers
│   └──── environment.rb
├──── db
│   ├──── migrate
│   └──── seeds.rb
├──── lib
│   └──── .gitkeep
└──── public
|   ├──── images
|   ├──── javascripts
|   └──── stylesheets
|       └───── main.css
└──── spec
    ├──── application_controller_spec.rb
    └──── spec_helper.rb
Enter fullscreen mode Exit fullscreen mode

For the next few days I will go over each file/ directory in a sinatra app. Today we will review:

config.ru

When you google what is config.ru you will get answers like this:

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.

If you are like me and prefer English, then in simple terms. Config.ru is where your application runs. It is what rack searches for to run your controllers and environment.

For a simple application, a config.ru usually looks similar to this:

require './config/environment'

use Rack::MethodOverride
use YourController
run ApplicationController
Enter fullscreen mode Exit fullscreen mode

use versus run

use is for middlewares and run takes an argument that responds to call and returns a final Rack response with a HTTP Response code like 200.

This can be pretty confusing but in short, run makes a call and receives a response and you do not want to run a controller multiple times. So in most cases, you will run your application controller and use any other controllers that you create for simple applications.

What is Rack::MethodOverride?

Rack::MethodOverride allows the method to be overridden if params[:_method] is set. This is the middleware which supports the PUT and DELETE HTTP method types.

I know, I know -- English. In short, this function helps to support PUT, DELETE, and PATCH request by allowing the application to "trick" the method into thinking it is a GET or POST request.

This will be explained further in a future post when I review CRUD and the views directory, but for know just know that it helps to make PUT DELETE and PATCH requests.

Resources

Rails on Rack

Stack Overflow

Stack Overflow

Top comments (0)