# What Happens When You Call render? Let's Understand the Rails Rendering Process

*Published on December 29, 2022*

Tags: Rails Internals

---


_This post assumes an understanding of metaprogramming concepts in Ruby. If you aren't comfortable with it, an excellent place to start is by reading the book_&nbsp;[_Metaprogramming Ruby 2_](/metaprogramming-ruby)_._

Ruby on Rails makes it very easy to render JSON data from the controller using the&nbsp;`render`&nbsp;method.

![render.png](https://writesoftwarewell.com/media/tq9szihhzm1licr3ssv0jf1rew5f.png "Render in Rails")

Ever wondered what really goes on behind the scenes? How does the&nbsp;`render`&nbsp;method convert the list of tasks to JSON format and sends it in the response? How Rails creates the renderers? This article will try to explain how rendering works in Rails.

By the end of the article, you should have a much better understanding of what really happens when you call the&nbsp;`render`&nbsp;method from the controller.

* * *

Let's start our journey into the rendering process by considering the Rails controller hierarchy.

Your typical Rails controllers inherit from the&nbsp;`ApplicationController`&nbsp;class which itself inherits from the&nbsp;`ActionController::Base`&nbsp;class. This class includes the&nbsp;`AbstractController::Rendering`&nbsp;module, providing the&nbsp;`render`&nbsp;method. Hence the&nbsp;`render`&nbsp;method becomes available in all your controllers.

![rails-controllers.png](https://writesoftwarewell.com/media/463is5lpp2qcq7ag507hoierp3ts.png "Rails Controller Hierarchy")

When you call&nbsp;`render`&nbsp;from the&nbsp;`PostsController`, Rails calls the `AbstractController::Rendering#render`&nbsp;method and sets its result on the response.

```ruby
class PostsController < ApplicationController
  def show
    @post = Post.first
    render json: @post
  end
end

# actionpack/lib/abstract_controller/rendering.rb

module AbstractController
  module Rendering
    def render(*args, &block)
      options = _normalize_render(*args, &block)
      rendered_body = render_to_body(options)
      self.response_body = rendered_body
    end
  end
end
```

The&nbsp;`normalize_render`&nbsp;method creates the hash of options containing the passed data&nbsp;`@posts`&nbsp;along with the template and the layout. It looks like this:

```ruby
options = {
  :json=>#<Post:0x00000001145d0470>,
  :template=> ..,
  :layout=> ..
}
```

Ignore the&nbsp;`template`&nbsp;and&nbsp;`layout`&nbsp;keys for now. The important point is that the `options[:json]` contains the post object we passed in the controller.

Now let's move to the next line in the&nbsp;`render`&nbsp;method, which calls the&nbsp;`render_to_body`&nbsp;method, passing the&nbsp;`options`&nbsp;hash. This method resides in the &nbsp;`action_controller/metal/renderers.rb`&nbsp;file.

```rust
# action_controller/metal/renderers.rb

module ActionController
  module Renderers
    def render_to_body(options)
      _render_to_body_with_renderer(options) || super
    end
  end
end
```

The&nbsp;`_render_to_body_with_renderer`&nbsp;method loops over a set of pre-defined renderers and checks if it includes the renderer we need (`:json`&nbsp;in our case). If it does, then it dynamically generates and calls a method named&nbsp;`method_name`&nbsp;using the&nbsp;[`Object#send`](https://ruby-doc.org/core-3.1.1/Object.html#method-i-send)&nbsp;method.

```ruby
# action_controller/metal/renderers.rb

module ActionController
  module Renderers
    def _render_to_body_with_renderer(options)
      _renderers.each do |name|
        if options.key?(name)
          _process_options(options)
          method_name = Renderers._render_with_renderer_method_name(name)
          return send(method_name, options.delete(name), options)
        end
      end
      nil
    end
  end
end
```

To understand this method, we need two pieces of information:

1. How renderers are initialized in the&nbsp;`_renderers`&nbsp;variable.
2. How&nbsp;`method_name`&nbsp;is generated and what it does when called.

**The**&nbsp;**`_renderers`**&nbsp;**variable**

It's a&nbsp;`Set`&nbsp;containing renderer names that correspond to available renderers. Default renderers are&nbsp;`json`,&nbsp;`js`, and&nbsp;`xml`.

This variable is defined in the&nbsp;`Renderers::All`&nbsp;concern. As soon as it's included in the&nbsp;`Base`&nbsp;class, it includes the&nbsp;`ActionController::Renderers`&nbsp;module. This module sets up the&nbsp;`RENDERERS`&nbsp;variable to an empty set and then calls the&nbsp;`add`&nbsp;method which fills this set.

```ruby
# action_controller/metal/renderers.rb

module ActionController
  module Renderers
    RENDERERS = Set.new
  
    module All
      extend ActiveSupport::Concern
      include Renderers
      
      included do
        self._renderers = RENDERERS
      end
    end
    
    add :json do |json, options|
      json.to_json(options) # simplified
    end
    
    add :xml { ... }
    
    add :js { ... }
  end
end
```

The&nbsp;`add`&nbsp;method takes the name of the renderer (`:json`) and a block, and

1. Dynamically defines a method that will execute the block later.
2. Add the name of the renderer to&nbsp;`RENDERERS`, a set of renderer names.

```ruby
# action_controller/metal/renderers.rb

module ActionController
  module Renderers
    def self.add(key, &block)
      define_method(_render_with_renderer_method_name(key), &block)
      RENDERERS << key.to_sym
    end
  end
end
```

Finally, the&nbsp;`RENDERERS`&nbsp;variable contains this array:&nbsp;`[:json, :js, :xml]`&nbsp;which gets assigned to the&nbsp;`_renderers`&nbsp;variable.

This brings us to the next point, that is, how the method named&nbsp;`method_name`&nbsp;is generated.

**How method\_name is generated**

Let's inspect the above&nbsp;`add`&nbsp;method in detail. It defines a method dynamically using the&nbsp;[`Module#define_method`](https://ruby-doc.org/core-3.1.1/Module.html#method-i-define_method)&nbsp;and passes it a name which it generates using the&nbsp;`_render_with_renderer_method_name`&nbsp;helper.

```ruby
def self._render_with_renderer_method_name(key)
  "_render_with_renderer_#{key}"
end
```

Passing&nbsp;`:json`&nbsp;will return the string&nbsp;`_render_with_renderer_json`. This is the name of the dynamic method. Its body is the block we passed to the&nbsp;`add`&nbsp;method.

To summarize, calling&nbsp;`add :json`&nbsp;as above defines the following method:

```ruby
def _render_with_renderer_json(json, options)
  json.to_json(options)  # simplified
end
```

And this gives us the final piece of the puzzle:&nbsp;**What the method defined by**&nbsp;**`method_name`**&nbsp;**does when called.**&nbsp;It simply calls&nbsp;`to_json`&nbsp;on the object you passed to the&nbsp;`render`&nbsp;method and returns it.

**To generalize, it renders the given object, depending on the renderer.**

Let's unwind the stack and go back to where we started, the&nbsp;`render_to_body_with_renderer`&nbsp;method.

```ruby
# action_controller/metal/renderers.rb

module ActionController
  module Renderers
    def _render_to_body_with_renderer(options)
      _renderers.each do |name|
        if options.key?(name)
          _process_options(options)
          method_name = Renderers._render_with_renderer_method_name(name)
          return send(method_name, options.delete(name), options)
        end
      end
      nil
    end
  end
end
```

As we saw earlier, the&nbsp;`options`&nbsp;hash looks like this:

```ruby
options = {
  :json=>#<Post:0x00000001145d0470>,
  :template=> ..,
  :layout=> ..
}
```

Since&nbsp;`options`&nbsp;contains the&nbsp;`:json`&nbsp;renderer, the control enters the if conditional block and calls the dynamically generated&nbsp;`_render_with_renderer_json`&nbsp;method. Additionally, it passes the value corresponding to the&nbsp;`:json`&nbsp;key, which is an instance of the&nbsp;`Post`&nbsp;class.

Let's revisit the dynamically generated&nbsp;`_render_with_renderer_json`&nbsp;method body again.

```ruby
def _render_with_renderer_json(json, options)
  json.to_json(options)
end
```

It will call&nbsp;`post.to_json`&nbsp;and return the following output.

```javascript
"{\"title\":\"hello world\"}"
```

Let's unwind the stack once more and return to the&nbsp;`render`&nbsp;method we saw at the beginning.

```ruby
# abstract_controller/rendering.rb (simplified)

def render(*args, &block)
  options = _normalize_render(*args, &block)
  rendered_body = render_to_body(options)
      
  self.response_body = rendered_body
end
```

The above JSON string is assigned to the&nbsp;`response_body`&nbsp;on the controller, which is ultimately sent to the client.

If you're curious how&nbsp;`response_body`&nbsp;actually works, keep on reading.

### Sending Response

Let's inspect the Rails controller hierarchy once again.

![rails-controllers.png](https://writesoftwarewell.com/media/yodhrm4djuewjhp7k3l7ujfon5zg.png "The Rails Controller Hierarchy")

Ultimately, your&nbsp;`PostsController`&nbsp;class inherits from the&nbsp;`ActionController::Metal`&nbsp;class. To learn more about the metal controller, check out the following article: [Metal Controller in Rails](/ruby-method-to-rails-action-metal)

The&nbsp;`ActionController::Metal`&nbsp;class provides the setter for the&nbsp;`response_body`, which assigns the value to the&nbsp;`response`&nbsp;body.

```ruby
# action_controller/metal.rb

module ActionController
  class Metal
    def response_body=(body)
      body = [body] unless body.nil? || body.respond_to?(:each)

      if body
        response.body = body
        super
      else
        response.reset_body!
      end
    end
  end
end
```

This whole request lifecycle was part of the&nbsp;`dispatch`&nbsp;method. Once the action is processed, the&nbsp;`dispatch`&nbsp;method calls&nbsp;`to_a`&nbsp;method, returning the&nbsp;`response.to_a`&nbsp;result.

```ruby
# action_controller/metal.rb

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

The&nbsp;`to_a`&nbsp;method on the&nbsp;`Response`&nbsp;calls the&nbsp;`rack_response`&nbsp;method, which returns the final result, the Rack-compatible array of the status, headers, &nbsp;and body. To learn more about Rack, check out the following article: [The Definitive Guide to Rack for Rails Developers](/definitive-guide-to-rack)

```rust
# action_dispatch/http/response.rb

module ActionDispatch
  class Response
    def to_a
      rack_response @status, @header.to_hash
    end
    
    def rack_response(status, header)
      [status, header, RackBody.new(self)]
    end
  end
end
```

Which ultimately returns the following JSON you see in the browser.

![json.png](https://writesoftwarewell.com/media/09ttx9mpvjhff2bdwl890hr7mfch.png "JSON")

## Conclusion

Whenever we invoke the following method in our application

```ruby
render json: @post
```

it invokes the block associated with the&nbsp;`:json`&nbsp;renderer.

```ruby
add :json do |json, options|
  json.to_json(options) # simplified version
end
```

The local variable&nbsp;`json`&nbsp;inside the block points to the&nbsp;`@post`&nbsp;object, and the other options passed to&nbsp;`render`&nbsp;will be available in the&nbsp;`options`&nbsp;variable. The block returns the JSON representation of the post and sends it to the client.

And that's what happens when you call&nbsp;`render json: @post`&nbsp;from your controller.

