Proposed Feature Addition: RespondTo Annotation #10
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hi there,
I have a proposed feature addition for Play. I created an annotation in play.mvc called RespondTo. The annotation is used to specify which formats a Controller or Action will respond to automatically.
Here is a quick example of usage:
@RespondTo({"json","xml"})
public class Articles extends Controller {
When a request comes in for Articles/show (or Articles/index) and the format requested is either "json" or "xml", then renderJSON or renderXml will be called on the args if there is no show.json or show.xml view. This keeps our action methods DRY and concise because we can avoid copying this all over the place:
if(request.format.equals("json")){
renderJSON(myModel);
}else if(request.format.equals("xml")){
renderXml(myModel);
}
And we don't have to create and maintain a bunch of .json and .xml versions of our views (If the views do exist they will take precedence though).
Also, RespondTo annotations defined at the action level will take precedence over RespondTo annotations on the controller.
So in this example:
@RespondTo({"json","xml"})
public class Articles extends Controller {
Articles/index will respond to json or xml automatically, while Articles/show will only respond to xml automatically (if json was requested and there is no .json view then it will just raise a TemplateNotFoundException like normal)
So yeah, that's what I've been playing around with on my fork. It's heavily inspired by Ruby on Rail's new respond_to decorator, and it helps me maintain flexible APIs while keeping my controllers concise and DRY.
And I just want to add that I'm absolutely loving Play so far, you guys have done a really great job with this framework. I'm trying to convince my team at work to migrate our website (which is currently PHP/Java) over to Play.