# How a Ruby Method Becomes a Rails Action: Part One

*Published on January 04, 2025*

Tags: Rails Internals

---


As a Rails developer, you probably know what the following piece of code does.

```ruby
# config/routes.rb

get "/about", to: "pages#about"

# controllers/pages_controller.rb

class PagesController < ApplicationController
  def about
    @title = "About Me"
  end
end

# views/pages/about.html.erb

<h1><%= @title %><h1>
```

As expected, it defines a route that directs a request to&nbsp;`/about`&nbsp;page to the&nbsp;`PagesController#about`&nbsp;method, which sets an instance variable&nbsp;`@title`&nbsp;that's displayed by the&nbsp;`about.html.erb`&nbsp;view.

Plain and simple.

Have you ever wondered how does an incoming HTTP request reaches the&nbsp;`about`&nbsp;method in the Rails controller? Like, who actually calls this method, what really happens before this method action is called? What happens afterwords?

This is something I used to be curious about ever since my ASP.NET MVC days, many years ago. But I never dared open&nbsp;[the source code](https://github.com/aspnet/AspNetWebStack/tree/main/src)&nbsp;and take a peek at what was going on under the hood.

But now that I work with Rails, a framework written in the most beautiful (and readable) programming language (for me),&nbsp;[reading the Rails source code](/tag/rails-internals)&nbsp;has become one of my favorite hobbies, and in this post, we're going to learn exactly how a simple Ruby method is promoted to a Rails action, armed with magical super powers to process incoming HTTP requests and generate responses.

Before we begin, it's important to note that there are a few different ways in which you can direct a request to a controller action in Rails. In part one (this post), we'll explore the more explicit (and simpler to understand) approach, where we manually mark the method as an action. In the part two of the post, we'll explore the traditional and 'conventional' way (the example shown above), where Rails automatically figures it out.

I wanted to include part two in the same post, but it got way too big, and I doubt anyone would've stuck around till the end. So here it goes.

* * *

Let's begin our journey with the controller. To be precise, the great-grandfather of the&nbsp;`PostsController`&nbsp;class.

All Rails controllers in your application inherit from the&nbsp;`ApplicationController`&nbsp;class, which inherits from&nbsp;`ActionController::Base`&nbsp;class. This class itself inherits from the&nbsp;`ActionController::Metal`&nbsp;class.

![rails_controllers.webp](https://writesoftwarewell.com/media/q8i4ol4t7w6p26ual1127imkoyxz.webp "Rails Controllers")

The&nbsp;`ActionController::Metal`&nbsp;class is a stripped-down version of the&nbsp;`ActionController::Base`&nbsp;class. If you didn't know, you can use it to build a simple controller as follows:

```ruby
class HelloController < ActionController::Metal
  def index
    self.response_body = "Hello World!"
  end
end
```

All we're doing is setting the body of the response which will be sent to the client.

💡 To keep things simple, we'll only explore how the incoming request reaches to the action method. What happens to the response, i.e., who uses the&nbsp;`response_body`&nbsp;above, will be covered in a future post.

**To use this**&nbsp;**`index`**&nbsp;**method as an action, we need to explicitly tell the router:**

```ruby
Rails.application.routes.draw do
  get 'hello', to: HelloController.action(:index)
end
```

**Note:**&nbsp;To re-iterate, this is not how you write your routes in practice. I am just showing this to teach how a barebones Rails metal controller can handle requests.

So it seems like the&nbsp;`action`&nbsp;method does the heavy lifting of promoting a Ruby method&nbsp;`index`&nbsp;into a Rails action. Let's see what it does.

### The action method

The&nbsp;`action`&nbsp;method returns a Rack application, an object that implements&nbsp;[the Rack interface](/definitive-guide-to-rack). To learn more about Rack, check out the following post: [https://www.writesoftwarewell.com/definitive-guide-to-rack](/definitive-guide-to-rack)

Here’s the body of the&nbsp;`action`&nbsp;method. Remember, the value of&nbsp;`name`&nbsp;argument is&nbsp;`:index`, the name of the method in the controller.

```ruby
# actionpack/lib/action_controller/metal.rb

# Returns a Rack endpoint for the given action name.
def self.action(name)
  app = lambda { |env|
    req = ActionDispatch::Request.new(env)
    res = make_response! req
    new.dispatch(name, req, res)
  }
  
  if middleware_stack.any?
    middleware_stack.build(name, app)
  else
    app
  end
end
```

The Rack application returned by the&nbsp;`action`&nbsp;method does the following.

- Create a new HTTP&nbsp;`Request`&nbsp;using the Rack environment&nbsp;`env`&nbsp;object.
- Call the&nbsp;`make_response!`&nbsp;method, passing the request. The&nbsp;`make_response!`&nbsp;method generates an&nbsp;`ActionDispatch::Response`&nbsp;object and assigns the request to it.

```ruby
# actionpack/lib/action_controller/metal.rb

def self.make_response!(request)
  ActionDispatch::Response.new.tap do |res|
    res.request = request
  end
end
```

- Finally, it creates a new instance of the controller class and dispatches (sends) the request and response objects to the action (`index`&nbsp;in our case).

```ruby
new.dispatch(name, req, res)
```

**Remember:**&nbsp;When we call the&nbsp;`new`&nbsp;method, we're still in the context of a controller class such as&nbsp;`PostsController`, so think of the above code as&nbsp;`PostController.new.dispatch(:index, req, res)`. Makes sense?

To continue the above example, upon receiving a request to&nbsp;`/hello`, the Rails router dispatches the request to this Rack app. To be precise, it calls the action method&nbsp;`:index`&nbsp;referenced by the&nbsp;`name`&nbsp;variable, which builds and returns the response.

Let's see what the&nbsp;`dispatch`&nbsp;method does.

### Dispatching the Action

The&nbsp;`dispatch`&nbsp;method takes the name of the action i.e.&nbsp;`:index`, the request object, and the response object as arguments. It returns the Rack response, which is an array containing the status, headers, and the response body.

```ruby
# actionpack/lib/action_controller/metal.rb

def dispatch(name, request, response)
  set_request!(request)
  set_response!(response)
  process(name)
  request.commit_flash
  to_a
end
```

The first two lines set the internal controller instance variables for request and response (for later use). Then, the&nbsp;`process`&nbsp;method, which is defined in the&nbsp;`AbstractController::Base`&nbsp;class, calls the action going through the entire action dispatch stack.

```ruby
# actionpack/lib/abstract_controller/base.rb

def process(action, ...)
  @_action_name = action.to_s
  
  unless action_name = _find_action_name(@_action_name)
    raise ActionNotFound.new("The action '#{action}' could not be found for #{self.class.name}", self, action)
  end
  
  @_response_body = nil
  
  process_action(action_name, ...)
end
```

The&nbsp;`process_action`&nbsp;method calls the method to be dispatched.

```ruby
# lib/abstract_controller/base.rb

def process_action(...)
  send_action(...)
end
```

The&nbsp;`send_action`&nbsp;is an alias to the&nbsp;[`Object#send`](https://ruby-doc.org/core-3.1.1/Object.html#method-i-send)&nbsp;method, which actually calls the method associated with the action.

```ruby
# lib/abstract_controller/base.rb

# Actually call the method associated with the action.
alias send_action send
```

Typically, you invoke the&nbsp;`send`&nbsp;method on an object, like&nbsp;`obj.send(:hello)`&nbsp;which will call the&nbsp;`hello`&nbsp;method on the&nbsp;`obj`&nbsp;instance. In this case, however, as we didn’t specify an object, it calls it on the&nbsp;`self`&nbsp;object, which is the instance of the&nbsp;`HelloController`. Hence, it calls the&nbsp;`HelloController#index`&nbsp;method.

💡 To summarize, an action is a logical concept in Rails (and other frameworks) representing an event (or an action) caused by the user (such as clicking a link or posting a form). The framework does the heavy lifting of eventually mapping this action to a Ruby method which handles that user event.

## Processing the Action

Now let’s inspect our&nbsp;`index`&nbsp;action method. All it does is set the&nbsp;`response_body`&nbsp;on&nbsp;`self`, which is an instance of&nbsp;`HelloController`.

```ruby
def index
  self.response_body = "Hello World!"
end
```

Let’s walk upwards in the stack. If you remember, our action was called by the&nbsp;`AbstractController::Base#process`&nbsp;method, which was invoked by the&nbsp;`ActionController::Metal#dispatch`&nbsp;method. Let’s continue where we left off in the&nbsp;`dispatch`&nbsp;method.

```ruby
def dispatch(name, request, response) # :nodoc:
  set_request!(request)
  set_response!(response)
  process(name)  # **we are here!**
  request.commit_flash
  to_a
end
```

After calling&nbsp;`process(name)`, the&nbsp;`response_body`&nbsp;is now set. The&nbsp;`Request#commit_flash`&nbsp;method deals with the&nbsp;[flash](https://api.rubyonrails.org/classes/ActionDispatch/Flash.html), which we’ll ignore for now. Finally, it calls the&nbsp;`to_a`&nbsp;method, which delegates to the&nbsp;`to_a`&nbsp;method on the response.

```ruby
def to_a
  response.to_a
end
```

## Sending the Response

The&nbsp;`ActionDispatch::Response#to_a`&nbsp;method turns the&nbsp;`Response`&nbsp;into a Rack response, i.e. an array containing the status, headers, and body.

```ruby
def to_a
  commit!
  rack_response @status, @header.to_hash
end
```

The&nbsp;`rack_response`&nbsp;method generates the body using the&nbsp;[`RackBody`](https://api.rubyonrails.org/classes/ActionDispatch/Response/RackBody.html)&nbsp;class, which responds to the&nbsp;`each`&nbsp;method, as it’s part of the&nbsp;[Rack specification](https://github.com/rack/rack/blob/main/SPEC.rdoc#the-body-).

💡 The body must respond to&nbsp;`each`&nbsp;or&nbsp;`call`. A Body that responds to&nbsp;`each`&nbsp;is considered to be an Enumerable Body. A Body that responds to&nbsp;`call`&nbsp;is considered to be a Streaming Body.

```ruby
def rack_response(status, header)
  if NO_CONTENT_CODES.include?(status)
    [status, header, []]
  else
    [status, header, RackBody.new(self)]
  end
end
```

So, ultimately, that’s how our simplest metal controller sends the response to an incoming HTTP request.

If you're curious, read the following post to learn more about the Rails rendering process.

[Understanding the Rails Rendering Process](/rails-rendering-process)

_This post was inspired from Phil Haack's post 16-year old post:_&nbsp;[_How a Method Becomes an Action_](https://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx/)&nbsp;_(in the context of ASP.NET)_

