O'Reilly logo

Crafting Rails 4 Applications, 2nd Edition by José Valim

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Writing the Renderer

At the beginning of this chapter, we briefly discussed the render method and a few options that it accepts, but we haven’t formally described what a renderer is.

A renderer is nothing more than a hook exposed by the render method to customize its behavior. Adding our own renderer to Rails is quite simple. Let’s consider the :json renderer in Rails source code as an example:

rails/actionpack/lib/action_controller/metal/renderers.rb
 
add :json ​do​ |json, options|
 
json = json.to_json(options) ​unless​ json.kind_of?(String)
 
if​ options[:callback].present?
 
self.content_type ||= Mime::JS
 
"​#{options[:callback]}​(​#{json}​)"
 
else
 
self.content_type ||= Mime::JSON
 
json
 
end
 
end

So, whenever we invoke the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required