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 ...
Get Crafting Rails 4 Applications, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.