Extract methods in link list component

Since we're simplifying the main method, we can use a view file instead
of the `call` method. This way we make the code more consistent with the
rest of our components, since we always use a separate file.

Doing so generates an extra newline at the end of the generated HTML, so
we need to change a couple of tests a little bit.
This commit is contained in:
Javi Martín
2021-06-26 23:14:45 +02:00
parent d0243764a2
commit 7abca09e03
3 changed files with 13 additions and 8 deletions

View File

@@ -0,0 +1 @@
<%= tag.ul(options) { safe_join(list_items, "\n") } %>

View File

@@ -7,12 +7,17 @@ class Shared::LinkListComponent < ApplicationComponent
end end
def render? def render?
links.select(&:present?).any? present_links.any?
end end
def call private
tag.ul(options) do
safe_join(links.select(&:present?).map do |text, url, current = false, **link_options| def present_links
links.select(&:present?)
end
def list_items
present_links.map do |text, url, current = false, **link_options|
tag.li(({ "aria-current": true } if current)) do tag.li(({ "aria-current": true } if current)) do
if url if url
link_to text, url, link_options link_to text, url, link_options
@@ -20,7 +25,6 @@ class Shared::LinkListComponent < ApplicationComponent
text text
end end
end end
end, "\n") end
end end
end
end end

View File

@@ -21,7 +21,7 @@ describe Shared::LinkListComponent, type: :component do
expect(list).to eq '<ul class="menu">' + "\n" + expect(list).to eq '<ul class="menu">' + "\n" +
'<li><a href="/">Home</a></li>' + "\n" + '<li><a href="/">Home</a></li>' + "\n" +
'<li><a href="/info">Info</a></li>' + "\n</ul>" '<li><a href="/info">Info</a></li>' + "\n</ul>\n"
end end
it "accepts anchor tags" do it "accepts anchor tags" do
@@ -32,7 +32,7 @@ describe Shared::LinkListComponent, type: :component do
expect(list).to eq '<ul class="menu">' + "\n" + expect(list).to eq '<ul class="menu">' + "\n" +
'<li><a href="/">Home</a></li>' + "\n" + '<li><a href="/">Home</a></li>' + "\n" +
'<li><a href="/info">Info</a></li>' + "\n</ul>" '<li><a href="/info">Info</a></li>' + "\n</ul>\n"
end end
it "accepts options for links" do it "accepts options for links" do