Skip to content

Instantly share code, notes, and snippets.

@ltello
Created May 9, 2012 17:49
Show Gist options
  • Save ltello/2647251 to your computer and use it in GitHub Desktop.
Save ltello/2647251 to your computer and use it in GitHub Desktop.
external links to tabs
module ActionView
module Helpers
module TextHelper
# Modify all html <a> tags in text to show them in a new browser's tab if they are externals to
# the domain of the url string opts[:except_site_host]
def external_links_to_tabs(text, opts = {})
text.gsub(A_LINK_RE) do
link, html_attrs = $&, $1
if href_to_this_site?(link, opts[:except_site_host].to_s)
link
else
new_html_attrs = [" target='_blank'", html_attrs.gsub(TARGET_RE, '')].join(' ')
link.sub!(html_attrs, new_html_attrs)
end
end
end
private
A_LINK_RE = /<a(\b.*?)>\w*<\/a>/i # Regexp to match an html <a...>...</a> tag
TARGET_RE = /target(\b)*\=(\b)*['"](\b.*?)['"]/i # Regexp to match an html target="something" tag's attribute
# Wether text include href='protocol://anysubdomains.domain' where:
# protocol:// is http://, https:// or nothing
# domain is the same main domain of the url string arg
def href_to_this_site?(text, url)
text =~ href_rexp_of_site(url)
end
# Returns a regexp to match the criteria above
def href_rexp_of_site(str_url)
href_prefix = "href(\b)*\=(\b)*"
protocol = "(\b)*(https?://)*"
subdomain = "((\\\w)+\.)*"
quote = "(\\\'|\\\")"
domain = extract_domain(str_url)
Regexp.new [href_prefix, quote, protocol, subdomain, domain, quote].join
end
# Extracts the domain.first_level_domain (e.g: ideas4all.com) part of a url given as string (ex: www1.ideas4all.com).
def extract_domain(str_url)
str_url.split('.').last(2).join('.')
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment