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:
1
app/components/shared/link_list_component.html.erb
Normal file
1
app/components/shared/link_list_component.html.erb
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<%= tag.ul(options) { safe_join(list_items, "\n") } %>
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
Reference in New Issue
Block a user