summaryrefslogtreecommitdiff
path: root/logic/cartridge/parser.rb
blob: 440c92930eaa31e364fc6288c8043343fa5af83c (about) (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# frozen_string_literal: true

require 'singleton'

require 'redcarpet'
require 'redcarpet/render_strip'

module NanoBot
  module Logic
    module Cartridge
      module Parser
        def self.parse(raw, format:)
          normalized = format.to_s.downcase.gsub('.', '')

          if %w[yml yaml].include?(normalized)
            yaml(raw)
          elsif %w[markdown mdown mkdn md].include?(normalized)
            markdown(raw)
          else
            raise "Unknown cartridge format: '#{format}'"
          end
        end

        def self.markdown(raw)
          yaml(Markdown.instance.render(raw))
        end

        def self.yaml(raw)
          Logic::Helpers::Hash.symbolize_keys(
            YAML.safe_load(raw, permitted_classes: [Symbol])
          )
        end

        class Renderer < Redcarpet::Render::Base
          def block_code(code, _language)
            "\n#{code}\n"
          end
        end

        class Markdown
          include Singleton

          attr_reader :markdown

          def initialize
            @markdown = Redcarpet::Markdown.new(Renderer, fenced_code_blocks: true)
          end

          def render(raw)
            @markdown.render(raw)
          end
        end
      end
    end
  end
end