Overview
This document records the code reading work for Ruby on Rails.
Preparation
- Create a new project with
rails new RailsCodeReading. - Add the following to the Gemfile:
gem 'pg'
gem 'pry-rails'
gem 'pry-doc'
gem 'pry-byebug'
gem 'byebug'
- Run
bundle config set path '.bundle', then executebundle install. - Run
rails generate controller Example. - Implement the index method in the controller:
def index
binding.pry
render json: { message: 'Hello World!' }
end
- Set up the routing:
get "example" => "example#index"
Code Reading
Let's trace how Rails processes requests.
By accessing http://127.0.0.1:3000/example and using pry-backtrace in the console, you can see the stack trace.
Since a lot of output is generated, we can't follow everything, so we'll skip through it.
- Puma accepts the request and calls the Rails application.
- puma/puma - lib/puma/request.rb#L99
- railties/lib/rails/engine.rb#L536
- Definition of the Rack API
- rack/rack - lib/rack/sendfile.rb#L113
- Rack application is executed.
- Based on the request information, the routing is resolved.
- rails/rails - actionpack/lib/action_dispatch/journey/router.rb#L126
- rails/rails - actionpack/lib/action_dispatch/routing/route_set.rb#L66
- Calls the processing of the controller that matched the routing.
- Calls the index of the controller.
It was more complex than I imagined, and since I'm not familiar with Ruby, I could only grasp the general idea...