Class: Plurimath::Mathml::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/plurimath/mathml/parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text) ⇒ Parser

Returns a new instance of Parser.



10
11
12
# File 'lib/plurimath/mathml/parser.rb', line 10

def initialize(text)
  @text = text
end

Instance Attribute Details

#textObject

Returns the value of attribute text.



8
9
10
# File 'lib/plurimath/mathml/parser.rb', line 8

def text
  @text
end

Instance Method Details

#parseObject



14
15
16
17
18
19
20
# File 'lib/plurimath/mathml/parser.rb', line 14

def parse
  ox_nodes = Ox.load(text, strip_namespace: true).nodes
  nodes = parse_nodes(ox_nodes)
  Math::Formula.new(
    Transform.new.apply(nodes).flatten.compact,
  )
end

#parse_nodes(nodes) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/plurimath/mathml/parser.rb', line 22

def parse_nodes(nodes)
  nodes.map do |node|
    next if node.is_a?(Ox::Comment)

    if node.is_a?(String)
      node
    elsif !node.attributes.empty?
      {
        node.name.to_sym => {
          attributes: node.attributes.transform_keys(&:to_sym),
          value: parse_nodes(node.nodes),
        },
      }
    else
      { node.name.to_sym => parse_nodes(node.nodes) }
    end
  end
end