Skip to content

Commit

Permalink
✅ Add parsing of URLs to post helper
Browse files Browse the repository at this point in the history
  • Loading branch information
adamdawkins committed Jan 22, 2019
1 parent fe6dcd7 commit 9478e4d
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
33 changes: 26 additions & 7 deletions app/helpers/posts_helper.rb
Expand Up @@ -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
10 changes: 10 additions & 0 deletions spec/helpers/posts_helper_spec.rb
Expand Up @@ -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.