How to use Ruby on Rails Presenter?
Whatis presenter?
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.
Let’s understand it in a better way through these codes-
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:->
JSON FORMAT OUTPUT-
While the above format output looks quite confusing and doesn’t look good.
Let’s learn about the reason behind it-
- The JSON response is very lengthy and not very read full.
- Null and useless data can be seen in JSON response which we don’t want to show.
- Encrypted attributes like password and other credentials also can be seen if they are used.
Thus these are the reasons we should use the presenters in rails to refactor the code of controllers
Now it’s time to create our JSON presenters
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
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.
The End
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 🙂