Sha256: 0ee334b4d154b2384f3e3506d0d3c5ab5c4cf9eb2f80e552c882b0e16dd120e4

Contents?: true

Size: 1.14 KB

Versions: 3

Compression:

Stored size: 1.14 KB

Contents

module Vapid
  class Template
    # HTML parser and DOM walker
    #
    # @todo Possibly use something other than Nokogiri, since it automatically adds DOCTYPE, etc
    class Parser
      attr_accessor :doc

      def initialize(html, initial_context)
        @doc = Nokogiri::HTML(html)
        @context_stack = [initial_context]
      end

      def walk(node = doc_root, set_context: nil, &block)
        if node.group?
          context = set_context.present? ? set_context.call(node.group_expr) : node.group_expr
          push_context(context)
        end

        yield(node, *@context_stack) if node.directives?

        next_node = node.first_child
        while next_node
          walk(next_node, set_context: set_context, &block)
          next_node = next_node.next_sibling
        end

        pop_context if node.group?
      end

      def to_html
        @doc.to_html
      end

      private

        def doc_root
          Node.new(@doc.first_element_child)
        end

        def push_context(context)
          @context_stack.unshift(context)
        end

        def pop_context
          @context_stack.shift
        end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
vapid-0.1.2 lib/vapid/template/parser.rb
vapid-0.1.1 lib/vapid/template/parser.rb
vapid-0.1.0 lib/vapid/template/parser.rb