1

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.

Jai Chauhan
  • 4,035
  • 3
  • 36
  • 62
Edi Junior
  • 49
  • 5

1 Answers1

2

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"
Michael Kosyk
  • 348
  • 1
  • 2
  • 10
  • @EdiJunior - no problem. I highly recommend learning a bit of Ruby before you jump into Ruby on Rails (a common mistake of many young developers is to learn a framework first, then the language). After that, grab the "Design Patterns in Ruby" book by Russ Olsen and listen to Sandi Metz on youtube. You won't regret it :) – Michael Kosyk Jun 10 '19 at 14:20