summaryrefslogtreecommitdiff
path: root/lib/banzai/filter/absolute_link_filter.rb
blob: 04ec568eee3085c1886a9888f1fd3647bcca18e4 (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
32
33
34
35
36
# frozen_string_literal: true

require 'uri'

module Banzai
  module Filter
    # HTML filter that converts relative urls into absolute ones.
    class AbsoluteLinkFilter < HTML::Pipeline::Filter
      def call
        return doc unless context[:only_path] == false

        doc.search('a.gfm').each do |el|
          process_link_attr el.attribute('href')
        end

        doc
      end

      protected

      def process_link_attr(html_attr)
        return if html_attr.blank?
        return if html_attr.value.start_with?('//')

        uri = URI(html_attr.value)
        html_attr.value = absolute_link_attr(uri) if uri.relative?
      rescue URI::Error
        # noop
      end

      def absolute_link_attr(uri)
        URI.join(Gitlab.config.gitlab.url, uri).to_s
      end
    end
  end
end