Class: Plurimath::Mathml::Parser

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

Constant Summary collapse

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text) ⇒ Parser

Returns a new instance of Parser.



21
22
23
# File 'lib/plurimath/mathml/parser.rb', line 21

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



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

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

#parse_nodes(nodes) ⇒ Object



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

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



54
55
56
57
# File 'lib/plurimath/mathml/parser.rb', line 54

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