On 20/10/2012, at 2:38 PM, Richard McGain <[email protected]> wrote: > I have just inherited a codebase and I am attempting to clean it up a bit. I > just can't figure out what to do with some controllers serving up json.
> I still don't think this justifies the use of some kind of template though ... Why not? IMHO generating API responses (JSON, or XML) is neither a controller concern, nor a model concern. After all, the response provided by a given API call is just one possible representation of the underlying data. > The obvious answer I guess, is to just define a method in > ApplicationController that looks something like > > def response_for(entity_name, collection) Sure, that's definitely a step forward from "collection.to_json". Perhaps don't stick them in ApplicationController, though; you could put them in modules and mix them into your controllers as required. > Does anyone have any better suggestions? Personally, I'd likely use a JSON-generating template, 'cos JSON representations are views, just as much as HTML pages are. I use RepresentativeView, because it's awesome (and I wrote it), but others prefer RABL, Jbuilder, or one of the many others. Most of these can also be used directly from Ruby, if you want to avoid putting stuff in "app/views". Using some kind of presenter, as Mark R suggests, is a pretty good approach, too. The Grape project defines a nice DSL (Grape::Entity) for defining presenters that expose JSON-ready data via "serializable_hash". I see no reason why you couldn't use it in a Rails project. Links: https://github.com/mdub/representative_view https://github.com/intridea/grape -- cheers, Mike Williams -- You received this message because you are subscribed to the Google Groups "Ruby or Rails Oceania" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/rails-oceania?hl=en.
