Presenters are part of view objects. Presenters are used in rails to refactor the response rendering to the views. According to MVC in rails, For most conventional RESTfulapplications, the controller will receive the request, fetch or save data from a model, and use a view to create HTML output. All presentation logics are pushed to the presenter.
Presenters are simple classes that sit between the controller and the view and provide a nice, DRY object-oriented way of working with complex display logic.
For e.g.: In the below controller, which has index API, normally the code will be like this-
This code provides all the information about the restaurant in JSON response like this:->
While the above format output looks quite confusing and doesn't look good.
Thus these are the reasons we should use the presenters in rails to refactor the code of controllers
Create folder named presenters in the app folder and create a new file restaurant_presenter.rb.
Add this code-
And update the index API like this:
And it gives JSON output like this
Now It is looking good and sophisticated as a JSON response.
If there is a user who belongs to a restaurant, then we can update the presenter response with the below code so we can get the information of a related user in the same restaurant JSON response also.
And update the API like this
The new JSON response for the above API will include the user's data which is added in UserPresenter.
As you can see, implementing your own clean JSON presenters is not that hard. However, We can also use great gems like Active Model Serializers or Jbuilder to build your JSON. This article is more for knowl
edge purposes. If you have very specific needs, you can now build your own JSON building solution using presenters based on this tutorial.
If you have any question,feel free to ask in comments.
Thank you :)