design-pattern-view-object

In this blog, we learned about View Objects (Presenter) Design Pattern.

In the previous blog, we talk about Ruby On Rails Design Patterns and Service Object Design Pattern. The main principle of software development is to keep the code DRY (Don’t Repeat Yourself) to reduce the reduction in the code, the design pattern helps us do the same.

Let’s talk about the View Object(Presenter) Design pattern.

View Objects allow us to encapsulate all view related logic and keep both models and views neat. The View should not contain calculation logic.
To solve the calculation logic problem, we can use rails helper, but if the complexity of the code is high, in that case, we should use the Presenter.

Let’s suppose we have a view page

User Full Name: <%= "#{user.first_name} #{user.last_name}"%> <%= link_to "View Profile", user, class: "w-75 p-3 text-#{user.active? ? 'green' : 'orange'} border-#{user.active? ? 'green' : 'orange'}"%>

Here we can see that we are concatenating the user’s first_name and last_name on the view. Which is not a good practice. Hence to solve this problem, we should use the presenter.

Let’s create a presenter class to solve this.

Class UserPresenter
  def initialize(user)
    @user = user
  end

  def full_name
    "#{@user.first_name} #{@user.last_name}"
  end

  def css_color
    @user.active? ? 'green' : 'orange'
  end
end

Save it under app/presenters/user_presenter.rb and create the presenter’s folder if you are not having it.

Now let’s change the view to make it more readable and without any calculations.

<% presenter = UserPresenter.new(user)%>User Full Name: <%= presenter.full_name%> <%= link_to "View Profile", user, class: "w-75 p-3 text-#{presenter.css_color} border-#{presenter.css_color}"%>

Now the view is more readable and easy to understand.
You can read about Ruby On Rails Design Pattern at https://runwithcode.blogspot.com/2020/04/design-patterns-in-ruby-on-rails.html

In the next blog, We will learn about the Query Objects Design Pattern.
Query Object is a type of design pattern that lets us fetch query logic from Controllers and Models into reusable classes


Thanks For Reading …

One thought on “Ruby On Rails Design Patterns Part 2 (View Objects)”

Leave a Reply

Your email address will not be published. Required fields are marked *