Sha256: 27e2ce3868f45272fa34b187d4082f991670fd1de31d2cc0d5c2c2217926b401

Contents?: true

Size: 1.33 KB

Versions: 3

Compression:

Stored size: 1.33 KB

Contents

module Pione
  module LiterateAction
    class Parser
      # Parse the source string and return the result.
      def self.parse(src)
        new(src).parse
      end

      def initialize(src)
        @src = src
      end

      # Parse the source string.
      def parse
        @parsed = Kramdown::Parser::GFM.parse(@src)
        current_name = nil
        root = @parsed.first
        root.children.each_with_object(Hash.new) do |elt, action|
          if name = find_rule_name(elt)
            current_name = name
            next
          end

          if current_name
            lang, content = find_action(elt)
            if content
              action[current_name] ||= {content: ""}
              action[current_name][:lang] = lang
              action[current_name][:content] << content
            end
          end
        end
      end

      private

      # Find a rule name from the element.
      def find_rule_name(elt)
        if elt.type == :header and elt.options[:level] == 2
          elt.options[:raw_text]
        end
      end

      # Find an action from the element.
      def find_action(elt)
        if elt.type == :codeblock
          if elt.attr["class"] and elt.attr["class"].start_with?("language-")
            return [elt.attr["class"].sub("language-", ""), elt.value]
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
pione-0.4.1 lib/pione/literate-action/parser.rb
pione-0.4.0 lib/pione/literate-action/parser.rb
pione-0.3.2 lib/pione/literate-action/parser.rb