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 ... |
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.