wiki_link_filter.rb 1.2 KB
Newer Older
G
Gabriel Mazetto 已提交
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
require 'uri'

module Banzai
  module Filter
    # HTML filter that "fixes" relative links to files in a repository.
    #
    # Context options:
    #   :project_wiki
    class WikiLinkFilter < HTML::Pipeline::Filter

      def call
        return doc unless project_wiki?

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

        doc
      end

      protected

      def project_wiki?
        !context[:project_wiki].nil?
      end

      def process_link_attr(html_attr)
28
        return if html_attr.blank? || file_reference?(html_attr)
G
Gabriel Mazetto 已提交
29 30

        uri = URI(html_attr.value)
31
        if uri.relative? && uri.path.present?
G
Gabriel Mazetto 已提交
32 33 34 35 36 37 38 39 40 41 42
          html_attr.value = rebuild_wiki_uri(uri).to_s
        end
      rescue URI::Error
        # noop
      end

      def rebuild_wiki_uri(uri)
        uri.path = ::File.join(project_wiki_base_path, uri.path)
        uri
      end

43 44 45 46
      def file_reference?(html_attr)
        !File.extname(html_attr.value).blank?
      end

G
Gabriel Mazetto 已提交
47 48 49 50 51 52 53 54 55 56
      def project_wiki
        context[:project_wiki]
      end

      def project_wiki_base_path
        project_wiki && project_wiki.wiki_base_path
      end
    end
  end
end