Permalink
Browse files

Add parsing of URLs to post helper

  • Loading branch information...
adamdawkins committed Jan 22, 2019
1 parent fe6dcd7 commit 9478e4d0bfa6a1b92f7eccc85aed88f5b96ef2f3
Showing with 36 additions and 7 deletions.
  1. +26 −7 app/helpers/posts_helper.rb
  2. +10 −0 spec/helpers/posts_helper_spec.rb
@@ -6,17 +6,36 @@ def auto_link_regex
end

def auto_link(content)
links = content.scan(auto_link_regex)
links.each do |link|
if link.start_with?("@")
# Twitter
content.gsub!(link, twitter_link(link))
addresses = content.scan(auto_link_regex)
addresses.each do |address|
uri = web_address_to_uri(address)
display_text = address

if address[0] == "@"
content.gsub!(address, autolink_tag(uri, display_text, "h-x-username"))
else
display_text = strip_protocol(display_text)
content.gsub!(address, autolink_tag(uri, display_text))
end
end
content
end

def twitter_link(username)
content_tag :a, username, class: "auto-link h-x-username", href: "https://twitter.com/#{username[1..-1]}"
def strip_protocol(url)
url.gsub(/http(s)?:\/\//, '')
end

def autolink_tag(url, text, classes = nil)
html_class = "auto-link"
html_class << " #{classes}" if classes
content_tag :a, text, class: html_class, href: url
end

def web_address_to_uri(wa)
return wa if (wa.start_with?('http://') || wa.start_with?('https://'))

return "https://twitter.com/#{wa[1..-1]}" if wa[0] == '@'

"http://" + wa
end
end
@@ -18,5 +18,15 @@
expect(helper.auto_link("@")).to eq '@'
end
end

context "URL" do
it "turns named links into URLs" do
expect(helper.auto_link("dragondrop.uk")).to eq '<a class="auto-link" href="http://dragondrop.uk">dragondrop.uk</a>'
end

it "strips protocol from displayed text" do
expect(helper.auto_link("https://dragondrop.uk")).to eq '<a class="auto-link" href="https://dragondrop.uk">dragondrop.uk</a>'
end
end
end
end

0 comments on commit 9478e4d

Please sign in to comment.