Class: Plurimath::Mathml::Parser

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

Constant Summary collapse

SUPPORTED_ATTRIBUTES =
%w[
  columnlines
  mathvariant
  mathcolor
  notation
  close
  open
].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text) ⇒ Parser

Returns a new instance of Parser.



19
20
21
# File 'lib/plurimath/mathml/parser.rb', line 19

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



23
24
25
26
27
28
29
30
31
# File 'lib/plurimath/mathml/parser.rb', line 23

def parse
  ox_nodes = Ox.load(text, strip_namespace: true)
  display_style = ox_nodes&.locate("*/mstyle/@displaystyle")&.first
  nodes = parse_nodes(ox_nodes.nodes)
  Math::Formula.new(
    Transform.new.apply(nodes).flatten.compact,
    displaystyle: display_style
  )
end

#parse_nodes(nodes) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/plurimath/mathml/parser.rb', line 33

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: validate_attributes(node.attributes),
          value: parse_nodes(node.nodes),
        },
      }
    else
      { node.name.to_sym => parse_nodes(node.nodes) }
    end
  end
end

#validate_attributes(attributes) ⇒ Object



52
53
54
55
# File 'lib/plurimath/mathml/parser.rb', line 52

def validate_attributes(attributes)
  attributes&.select! { |key, _| SUPPORTED_ATTRIBUTES.include?(key&.to_s) }
  attributes&.transform_keys(&:to_sym) if attributes&.any?
end