ruby-on-rails-5decoratorpresenter

Should I use a presenter or a decorator?


I'm kinda lost with these terms since I'm a beginner in the Rails world. I have some code in my header, not related to the model. I just want to show it or not depending on the page user is.

I know it's kinda simple and helpers would do it pretty well too, but is it possible to fit the code in a presenter or a decorator? When do I have to use them? I really don't understand it yet.


Solution

  • tl;dr: Use a Presenter in this scenario

    Elaboration: A Decorator is a structural design pattern that wraps other objects and adds new functionality without the need to extend the class you are decorating.

    A Presenter on the other hand should use methods of the object you are presenting to format data in a way you want to show them. Eg. you have a User model:

    class User < ActiveRecord:Base
      # it has first_name and last_name columns
    end
    

    and you want to present the full name without much logic in the views. You can create a UserPresenter class like this:

    class UserPresenter
      def initialize(user)
        @user = user
      end
    
      def full_name
        "#{@user.last_name} #{@user.first_name}"
      end
    end
    

    So instead of calling both attributes separately, you just do it with the presenter

    user = User.new(first_name: "John", last_name: "Doe")
    user_presenter = UserPresenter.new(user)
    user_presenter.full_name #=> "Doe John"