markdown_filter.rb 836 Bytes
Newer Older
1 2
# frozen_string_literal: true

3 4
module Banzai
  module Filter
5 6
    class MarkdownFilter < HTML::Pipeline::TextFilter
      def initialize(text, context = nil, result = nil)
7 8
        super(text, context, result)

9
        @renderer = renderer(context[:markdown_engine]).new(context)
10
        @text = @text.delete("\r")
11 12 13
      end

      def call
14 15 16 17 18
        @renderer.render(@text).rstrip
      end

      private

19
      DEFAULT_ENGINE = :common_mark
20 21 22 23 24

      def engine(engine_from_context)
        engine_from_context ||= DEFAULT_ENGINE

        engine_from_context.to_s.classify
25
      end
26

27 28 29 30
      def renderer(engine_from_context)
        "Banzai::Filter::MarkdownEngines::#{engine(engine_from_context)}".constantize
      rescue NameError
        raise NameError, "`#{engine_from_context}` is unknown markdown engine"
31
      end
32 33 34
    end
  end
end