Extract component to render a list of links

This way it's easier to refactor it and/or change it.

Back in commit c156621a4 I wrote:

> Generally speaking, I'm not a big fan of helpers, but there are
> methods which IMHO qualify as helpers when (...) many Rails helpers,
> like `tag`, follow these principles.

It's time to modify these criteria a little bit. In some situations,
it's great to have a helper method so it can be easily used in view
(like `link_to`). However, from the maintenance point of view, helper
methods are usually messy because extracting methods requires making
sure there isn't another helper method with that name.

So we can use the best part of these worlds and provide a helper so it
can be easily called from the view, but internally make that helper
render a component and enjoy the advantages associated with using an
isolated Ruby class.
This commit is contained in:
Javi Martín
2021-06-26 22:51:25 +02:00
parent 1a477eb511
commit d0243764a2
4 changed files with 120 additions and 104 deletions

View File

@@ -0,0 +1,26 @@
class Shared::LinkListComponent < ApplicationComponent
attr_reader :links, :options
def initialize(*links, **options)
@links = links
@options = options
end
def render?
links.select(&:present?).any?
end
def call
tag.ul(options) do
safe_join(links.select(&:present?).map do |text, url, current = false, **link_options|
tag.li(({ "aria-current": true } if current)) do
if url
link_to text, url, link_options
else
text
end
end
end, "\n")
end
end
end