The presenter is responsible for refining the HTML code of the logic in the View part. The point is, let's make the view part refreshing. Presenters are also called decorators.
It seems that Draper, Cells, etc. are used in Gem, We will implement it without using Gem this time.
Since it is a method used in the view, it is natural to define it as a helper method. But helper has its advantages and disadvantages that are globally defined. As the project grows, the risk of name conflicts increases.
This time, we will separate the logic part included in the following code. The logic of the criminal list. If "arrested?" Is true, add ☑️ and add ☑️. If not, it will be a blank □.
<% @members.each do |m| %>
<%= m.arrested? ? raw("☑") : raw("☐") %>
First, create the ModelPresenter class, which is the ancestor of all presenters. Call-only object and view_context attributes are defined.
app/presenters/model_presenter.rb
class ModelPresenter
attr_reader :object, :view_context
def initialize(object, view_context)
@object = object
@view_context = view_context
end
end
Next, create a Member presenter class by inheriting the model_presenter class.
member_presenter.rb
class StaffMemberPresenter < ModelPresenter
end
Edit the ERB template using this class. Create an instance of the MemberPresenter class.
The first argument of the new method is the Member object. The pseudo variable self is specified in the second argument. self can use all the helper methods defined in Rails.
<% @members.each do |m| %>
<% p = MemberPresenter.new(m, self) %>
<%= m.arrested? ? raw("☑") : raw("☐") %>
Here, we will define the instance method in the MemberPresenter class created earlier.
member_presenter.rb
class MemberPresenter < ModelPresenter
def arrested_mark
object.arrested? ?
view_context.raw("☑") :
view_context.raw("☐")
end
end
Make the view part refreshing by using the presenter so far
<% @members.each do |m| %>
<% p = MemberPresenter.new(m, self) %>
<%= p.arrested_mark %>
The following code is embedded in the changed part.
m.arrested? ? raw("☑") : raw("☐")
I was able to refresh the view like this. I would like to write the article again because using delegate makes it a little more concise. That's all for today.
Recommended Posts