summaryrefslogtreecommitdiff
path: root/lib/banzai/filter/external_link_filter.rb
blob: d179bea181e7f10385609a2ba7edcf16194ea7e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
module Banzai
  module Filter
    # HTML Filter to add a `rel="nofollow"` attribute to external links
    #
    class ExternalLinkFilter < HTML::Pipeline::Filter
      def call
        doc.search('a').each do |node|
          link = node.attr('href')

          next unless link

          # Skip non-HTTP(S) links
          next unless link.start_with?('http')

          # Skip internal links
          next if link.start_with?(internal_url)

          node.set_attribute('rel', 'nofollow')
        end

        doc
      end

      private

      def internal_url
        @internal_url ||= Gitlab.config.gitlab.url
      end
    end
  end
end