Skip to content

Commit

Permalink
extend link_to helper to accept blocks (#632)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexanderadam authored Oct 31, 2022
1 parent ab042e7 commit 54e6806
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
8 changes: 7 additions & 1 deletion bridgetown-core/lib/bridgetown-core/helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,13 @@ def find_relative_url_for_path(relative_path)
# @param options [Hash] key-value pairs of HTML attributes to add to the tag
# @return [String] the anchor tag HTML
# @raise [ArgumentError] if the file cannot be found
def link_to(text, relative_path, options = {})
def link_to(text, relative_path = nil, options = {})
if block_given?
relative_path = text
text = yield
elsif relative_path.nil?
raise ArgumentError, "You must provide a relative path"
end
segments = attributes_from_options({ href: url_for(relative_path) }.merge(options))

safe("<a #{segments}>#{text}</a>")
Expand Down
10 changes: 10 additions & 0 deletions bridgetown-core/test/test_ruby_helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@ def setup
should "accept hash attributes" do
assert_equal "<a href=\"/foo/bar\" class=\"classes\" data-controller=\"test\" data-action=\"test#test\">Label</a>", @helpers.link_to("Label", "/foo/bar", class: "classes", data: { controller: "test", action: "test#test" })
end

should "accept block syntax" do
assert_equal "<a href=\"/foo/bar\">Label</a>", @helpers.link_to("/foo/bar") { "Label" }
end

should "raise if only one argument was given" do
assert_raises ArgumentError do
@helpers.link_to("Label")
end
end
end

context "attributes_from_options" do
Expand Down

0 comments on commit 54e6806

Please sign in to comment.