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.
gem 'draper'
Also execute this.
$ budle install
$ rails generate draper:install
#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 %>
・
・
・
--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
Prepare a Decorator to display Rails View to help Helper and Model
About the role of Decorator and Draper
Recommended Posts