I'm trying to understand decorator patterns.
As I understand it, Decorators are concerned with 'presenting' the data of a model. They will encompass methods that can be called in the Views.
Up until now, I would have been throwing methods like that in the Helpers or just in the Models (if they need to be called on model instances). Is the main difference between Decorators and Helpers that Decorators are tied to a specific model, whereas Helpers can be more generic utility methods (like Date helpers and so on)?
What are helpers in Rails? A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words .
Decorator is a structural pattern that allows adding new behaviors to objects dynamically by placing them inside special wrapper objects, called decorators. Using decorators you can wrap objects countless number of times since both target objects and decorators follow the same interface.
In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.
What is 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 RESTful applications, the controller will receive the request, fetch or save data from a model, and use a view to create HTML output.
Rails' (built-in) way of organizing your code is: Fat models, skinny controllers, and throw the rest in Helpers (or Concerns, which are Helpers but for controllers/models).
Biggest problems with helpers (IMO):
@user.full_name
. Decorators:
Using the Decorator pattern will reduce the amount of code in the fat models (imposed by Rails' built-in way to do things):
link_to_icon(icon_name, *args)
, hours_from_datetime(datetime, format = '24')
, menu_link(name, path, *args)
, etc. If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With