[RAILS] Do you know Decorator?

What is a Decorator?

By wrapping an existing object with a new Decorator object, you can add or rewrite functionality from outside without having to touch the contents of an existing function or class. It is also used as an alternative to class inheritance when extending an existing class.

The role of converting "data (easy to manage by a program)" into "information (easy to understand by the user)". To use it, install and use a gem called "draper". Create files under app / decorators.

How to use

  1. Describe the following in the Gemfile.

gem 'draper'

Also execute this.


$ budle install
  1. Execute the following command to create application_decorator.rb.

$ rails generate draper:install
  1. Execute the following command to create a decorator.

#rails generate decorator model name

$ rails generate decorator Article

model

app/decorators/article_decorator.rb



class ArticleDecorator < Draper::Decorator
  delegate_all

  def publication_status
    if published?
      "Published at #{published_at.strftime("%A, %B %e")}"
    else
      "Unpublished"
    end
  end
end

View

・
・
・
<%= @article.publication_status %>
・
・
・

Tips

--Access the model instance


object.published_at.strftime("%A, %B %e")

model.published_at.strftime("%A, %B %e") #model is an alias for object

--Delegate all methods --Internally, method_missing is used for delegation. --Method search order: Decorator-> Parent decorator-> Model


class ArticleDecorator < Draper::Decorator
  delegate_all
end

--Delegate the specified method --The deleage method is almost the same as the Active Support delegate. However, to :: object can be omitted.


class ArticleDecorator < Draper::Decorator
  #In title, object.You will be able to access the title
  delegate :title, :body

  #Delegate the specified method to the specified object
  delegate :name, :title, to: :author, prefix: true
end

reference

Prepare a Decorator to display Rails View to help Helper and Model

About the role of Decorator and Draper

Summary of how to use Draper

Recommended Posts

Do you know Decorator?
Kinx Tiny Typesetting --LaTeX faction? Do you know?
Do you need dotenv-rails?
Java reserved word summary that you do not know unexpectedly
Convenient use of Map that you do not know unexpectedly
Can you do it? Java EE
When will you do the refactoring?
Do you use Stream in Java?
Do you know Carbon, which displays the source code coolly on Twitter?
How do you write the ternary operator (? :)
Basic Java grammar you should know first
What to do if you install Ubuntu