Search code examples
ruby-on-railsrubypresenter

How to present list of names in Presenter?


I have my custom presenter

class ShiftPresenter
  def initialize(shift, template)
    @shift = shift
    @template = template
  end

  def h
    @template
  end

  def users_list
    logs = ShiftLog.by_shift(@shift)
    names = logs.map do |log|
      log.cardiologist.name
    end
    h.content_tag :div, names unless names.empty?
  end
end

and #index view

- present shift do |shift_presenter|
  = shift_presenter.user_list

How to present users names using li instead of ['tom', 'jerry']


Solution

  • You can add this to your presenter method:

    def users_list
      logs = ShiftLog.by_shift(@shift)
      names = logs.map(&:cardiologist).map(&:name)#.compact.uniq # you can add this if you want
      h.content_tag :div do
        h.content_tag :ul do
          ul_content = ''.html_safe
          names.each do |name|
            ul_content << h.content_tag :li, name
          end
          ul_content
        end
      end
    

    The thing is it works as block with the return statement: the last used/returned object will be put inside the content_tag.