views:

44

answers:

2

That's my great doubt.

We have a project in RoR and we are making it more dynamic, using Ajax calls. They want that I put literal JSON in html templates and parse it with eval() in javascript, avoiding to putting exception into Controller to return response as JSON directly.

Example: WhateverControoler#index -> will render views/whatever_controller/index.html.erb (JSON literal in an html template):

{
"Success": "false",
"Date": ("need_login": "true")
}

What I suggest to use in WhateverControoler#index

render :json => (: success => false, :data => (:need_login => true))

Instead of putting it into Controller, they want me to use the template that Controller will render normally to show a literal JSON.

Some controllers have begin/raise blocks that redirects to other places, because of it I need put exceptions to render JSON instead redirct.

if (is_ajax) render :json[..] else redirect_to [..] end

I need an strong reason to avoid it and shows that's wrong.

This make sense? I tried to explain at best I can.

PS: I know that I could use "respond_to do |format|..." but I need as if statments because of the redirects, the code is already messy and they want to avoid messing up even more

+2  A: 

Avoid using templates if you can. Here's a good list of reasons:

  • If you use render :json, Rails will take care of the rest. It will setup the right mime type, convert the content and render a well formed JSON response.
  • Skipping template rendering increases performances.
  • JSON is designed to be a single-line response. If you render a template with a JSON-like response, you are probably going to return a less lightweight response.
Simone Carletti
A: 

From my point of view, the main flaw in generating json via erb is that you're not sure that your json will be valid (but this is the same problem with html i guess). You'll have to set the mime-type by yourself too.

to_json is well tested and you can thus expect that the output will be valid JSON.

The main problem with to_json is that it can't generate all the json you want and some have asked for a json builder for instance (see this ticket)

So my advice would be that as long as you are not limited by to_json use to_json in controller, and ultimately generate it via erb

hellvinz