Skip to content

Commit

Permalink
Handle malformed URLs gracefully
Browse files Browse the repository at this point in the history
  • Loading branch information
derrickreimer committed Feb 7, 2014
1 parent c05dfe3 commit 0af9f47
Show file tree
Hide file tree
Showing 7 changed files with 28 additions and 4 deletions.
6 changes: 6 additions & 0 deletions lib/bypass/filter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,11 @@ def gsub_urls(text, &block)
yield(match.to_s)
end
end

def parse_uri(uri)
Bypass::URI.parse(uri)
rescue => ex
nil
end
end
end
6 changes: 4 additions & 2 deletions lib/bypass/html_filter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ class HTMLFilter < Filter
def replace(&block)
parsed_content.traverse do |node|
if node.name == "a" && href = node.get_attribute("href")
url = yield(Bypass::URI.parse(href))
node.set_attribute("href", url.to_s)
if parsed_href = parse_uri(href)
url = yield(parsed_href)
node.set_attribute("href", url.to_s)
end
end
end
end
Expand Down
6 changes: 4 additions & 2 deletions lib/bypass/text_filter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ module Bypass
class TextFilter < Filter

def replace(&block)
@content = gsub_urls(content) do |url|
yield(Bypass::URI.parse(url)).to_s
@content = gsub_urls(content) do |url|
if parsed_url = parse_uri(url)
yield(parsed_url).to_s
end
end
end

Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ class Bypass::HTMLFilterTest < Test::Unit::TestCase
filter.replace { "foo" }
assert_equal "<a>Yahoo</a>", filter.content
end

should "skip malformed URLs" do
text = "<a href=\"http://#\">Yahoo</a>"
filter = Bypass::HTMLFilter.new(text)
filter.replace { "foo" }
assert_equal text, filter.content
end
end

context "#auto_link" do
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,12 @@ class Bypass::TextFilterTest < Test::Unit::TestCase
filter.replace { "foo" }
assert_equal "foo,", filter.content
end

should "skip malformed URLs" do
text = "http://#"
filter = Bypass::TextFilter.new(text)
filter.replace { "foo" }
assert_equal text, filter.content
end
end
end
File renamed without changes.

0 comments on commit 0af9f47

Please sign in to comment.