summaryrefslogtreecommitdiff
path: root/lib/banzai/filter/reference_unfold_filter.rb
blob: 70a485ba2ae4061ec063781a122b8d1ef1c71104 (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
37
38
39
40
41
42
require 'html/pipeline/filter'

module Banzai
  module Filter
    ##
    # Filter than unfolds local references.
    #
    #
    class ReferenceUnfoldFilter < HTML::Pipeline::Filter
      def initialize(*)
        super

        unless result[:references].is_a?(Hash)
          raise StandardError, 'References not processed!'
        end

        @text = context[:text].dup
        @new_project = context[:new_project]
        @referables = result[:references].values.flatten
      end

      def call
        @referables.each do |referable|
          next unless referable.respond_to?(:to_reference)

          pattern = /#{Regexp.escape(referable.to_reference)}/
          @text.gsub!(pattern, referable.to_reference(@new_project))
        end

        @text
      end

      private

      def validate
        needs :project
        needs :new_project
        needs :text
      end
    end
  end
end