What does rack do in rails?
Rails Overall Request response flow is shown in the above diagram.
Rack:
A modular interface between web servers and applications developed in the Ruby programming language. With Rack, application programming interfaces (APIs) for web frameworks and middleware are wrapped into a single method of handling HTTP requests and responses.?
Inside a Rails application, there is a stack of Rack middleware components. These components process the incoming request and the outgoing response.
Middleware can perform multiple tasks some of them are:
Logging: Capture and log details about incoming requests and outgoing responses.
Authentication: Check for valid user sessions or authentication tokens.
Caching: Cache responses to reduce server load and improve response times.
Error Handling: Catch and handle errors or exceptions in a standardized way.
Security: Implement security measures, such as request filtering or protection against common attacks like Cross-Site Scripting (XSS) or Cross-Site Request Forgery (CSRF).
Rails allows us to reconfigure the above stack during the initialization via changing config.middleware in application.rb.
To see which rack filters are enabled in our application, we can use:
rails middleware command and you will see something like the below.
> rails middleware
use Rack::Cors
use ActionDispatch::HostAuthorization
use Rack::Sendfile
use ActionDispatch::Static
use ActionDispatch::Executor
use ActionDispatch::ServerTiming
use ActiveSupport::Cache::Strategy::LocalCache::Middleware
use Rack::Runtime
use ActionDispatch::RequestId
use ActionDispatch::RemoteIp
use Rails::Rack::Logger
use ActionDispatch::ShowExceptions
use ActionDispatch::DebugExceptions
use ActionDispatch::ActionableExceptions
use ActionDispatch::Reloader
use ActionDispatch::Callbacks
use ActiveRecord::Migration::CheckPending
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
run MyApi::Application.routes
Simple Rack example:
Write the below lines of code in the config.ru file and just run rackup config.ru command in the command line interface. You will be able to see the result in browse if you navigate to URL https://localhost:9292/
require 'rack'
app= ->(env){ [200,{ 'Content-Type' => 'text/plain'}, ["Hello World"]]} run app