Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle links that have a blank or missing href #124

Merged
merged 1 commit into from
Feb 21, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions lib/govspeak/link_extractor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,22 @@ def call
attr_reader :document, :website_root

def extract_links
document_anchors.map do |link|
if website_root && link['href'].start_with?('/')
"#{website_root}#{link['href']}"
else
link['href']
end
document_anchors.
map { |link| extract_href_from_link(link) }.
reject(&:blank?)
end

def extract_href_from_link(link)
href = link['href'] || ''
if website_root && href.start_with?('/')
"#{website_root}#{href}"
else
href
end
end

def document_anchors
processed_govspeak.css('a:not([href^="mailto"])').css('a:not([href^="#"])')
processed_govspeak.css('a[href]').css('a:not([href^="mailto"])').css('a:not([href^="#"])')
end

def processed_govspeak
Expand Down
21 changes: 20 additions & 1 deletion test/govspeak_link_extractor_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,20 @@ def document_body
[mailto:](mailto:[email protected])

[absolute_path](/cais-trwydded-yrru-dros-dro)

<a href="http://www.example.com/from/html">raw_html_link</a>

[empty_markdown_link]()

[a_different_empty_markdown_link]( )

<a>empty_raw_html_link</a>

<a href="">a_second_empty_raw_link</a>

<a href=" ">a_third_empty_raw_link</a>

<a href>a_fourth_empty_raw_link</a>
}
end

Expand All @@ -26,7 +40,7 @@ def links
end

test "Links are extracted from the body" do
expected_links = %w{http://www.example.com http://www.gov.com /cais-trwydded-yrru-dros-dro}
expected_links = %w{http://www.example.com http://www.gov.com /cais-trwydded-yrru-dros-dro http://www.example.com/from/html}
assert_equal expected_links, links
end

Expand All @@ -42,6 +56,11 @@ def links
refute_includes ["mailto:[email protected]"], links
end

test "Links are not extracted if they are blank" do
refute_includes [""], links
refute_includes [nil], links
end

test "Absolute links are transformed to a url when website_root passed in" do
urls = doc.extracted_links(website_root: "http://www.example.com")
assert urls.include?("http://www.example.com/cais-trwydded-yrru-dros-dro")
Expand Down