From 31e53046bd35b83027f8a8e1ab99a6eceb4e6a3c Mon Sep 17 00:00:00 2001 From: icebaker Date: Mon, 8 Jan 2024 21:41:30 -0300 Subject: adding support to markdown cartridges --- logic/cartridge/parser.rb | 56 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 logic/cartridge/parser.rb (limited to 'logic/cartridge') diff --git a/logic/cartridge/parser.rb b/logic/cartridge/parser.rb new file mode 100644 index 0000000..440c929 --- /dev/null +++ b/logic/cartridge/parser.rb @@ -0,0 +1,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 -- cgit v1.2.3