This article is a continuation of Introducing Presenters.
This is the model presenter I made last time. I would like to add a delegate method to this presenter
model_presenter.rb
class ModelPresenter
attr_reader :object, :view_context
def initialize(object, view_context)
@object = object
@view_context = view_context
end
end
The class method delegate defines an instance method with the name specified in the argument. And the function of that method is entrusted to the object returned by the method specified in the to option.
This time we will delegate a method called raw to the object returned by view_context
model_presenter.rb
class ModelPresenter
attr_reader :object, :view_context
delegate :raw, to: :view_context
def initialize(object, view_context)
@object = object
@view_context = view_context
end
end
By the way, the member_presenter created last time was like this.
member_presenter.rb
class MemberPresenter < ModelPresenter
def arrested_mark
object.arrested? ?
view_context.raw("☑") :
view_context.raw("☐")
end
end
Using the delegate method made it cleaner.
member_presenter.rb
class MemberPresenter < ModelPresenter
def arrested_mark
object.arrested? ? raw("☑") : raw("☐")
end
end
Furthermore, if you outsource arrested? To object
member_presenter.rb
class MemberPresenter < ModelPresenter
delegate :arrested?, to: :object
def arrested_mark
arrested? ? raw("☑") : raw("☐")
end
end
Since the arrested? method is a unique object of the member object, I defined it at the inheritance destination. I was able to refresh the presenter by using delegate like this.
That's all for today !!
Recommended Posts