debian-mirror-gitlab/lib/banzai/filter/external_link_filter.rb

49 lines
1.1 KiB
Ruby
Raw Normal View History

2015-12-23 02:04:40 +05:30
module Banzai
module Filter
2016-06-02 11:05:42 +05:30
# HTML Filter to modify the attributes of external links
2015-09-11 14:41:01 +05:30
class ExternalLinkFilter < HTML::Pipeline::Filter
def call
2016-11-03 12:29:30 +05:30
links.each do |node|
href = href_to_lowercase_scheme(node["href"].to_s)
unless node["href"].to_s == href
node.set_attribute('href', href)
end
if href =~ /\Ahttp(s)?:\/\// && external_url?(href)
node.set_attribute('rel', 'nofollow noreferrer')
node.set_attribute('target', '_blank')
end
2015-09-11 14:41:01 +05:30
end
doc
end
private
2016-11-03 12:29:30 +05:30
def links
query = 'descendant-or-self::a[@href and not(@href = "")]'
doc.xpath(query)
end
def href_to_lowercase_scheme(href)
scheme_match = href.match(/\A(\w+):\/\//)
if scheme_match
scheme_match.to_s.downcase + scheme_match.post_match
else
href
end
end
def external_url?(url)
!url.start_with?(internal_url)
end
2015-09-11 14:41:01 +05:30
def internal_url
@internal_url ||= Gitlab.config.gitlab.url
end
end
end
end