Overview
Documenting the code reading process 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'and then executebundle install. rails generate controller Example- Add
binding.pryto railties/lib/rails/welcome_controller.rb#L9:
def index
binding.pry
end
Code Reading
Let's explore how Rails invokes WelcomeController#index.
config/routes.rb does not define WelcomeController#index; Rails seems to define it by default, likely through the autoload mechanism.
Autoloading it here registers WelcomeController in the routing.
Here is the implementation of WelcomeController. railties/lib/rails/welcome_controller.rb#L5
Although I couldn't follow the code in detail, Rails appears to leverage the autoload mechanism to resolve routing without explicitly registering it.