[Ruby] Rails delegate method

1 minute read

Use #delegate method 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. The work of that method is then delegated to the object returned by the method specified in the to option.

This time we 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("&#x2611"):
      view_context.raw("&#x2610")
  end
end

It became cleaner by using the delegate method.

member_presenter.rb


class MemberPresenter <ModelPresenter
  def arrested_mark
    object.arrested? ?raw("&#x2611"): raw("&#x2610")
  end
end

If you delegate the arrested?

member_presenter.rb


class MemberPresenter <ModelPresenter
  delegate :arrested?, to: :object
  def arrested_mark
    arrested? ?raw("&#x2611"): raw("&#x2610")
  end
end

Since the arrested? method is a unique object of the member object, I defined it in the inheritance destination. I was able to refresh the presenter by using delegate like this.

That’s all for today!!

Tags: ,

Updated: