Class: Plurimath::Omml::Parser

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

Constant Summary collapse

CUSTOMIZABLE_TAGS =
%w[
  eqArr
  mr
  r
].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text) ⇒ Parser

Returns a new instance of Parser.



15
16
17
# File 'lib/plurimath/omml/parser.rb', line 15

def initialize(text)
  @text = text
end

Instance Attribute Details

#textObject

Returns the value of attribute text.



7
8
9
# File 'lib/plurimath/omml/parser.rb', line 7

def text
  @text
end

Instance Method Details

#customize_tags(node) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/plurimath/omml/parser.rb', line 48

def customize_tags(node)
  case node.name
  when "r"
    organize_fonts(node)
  when "mr", "eqArr"
    organize_table_td(node)
  end
end

#organize_fonts(node) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/plurimath/omml/parser.rb', line 63

def organize_fonts(node)
  attrs_arr = { val: [] }
  node.locate("rPr/?").each do |child|
    attrs_arr[:val] << child.attributes["val"]
  end
  node.attributes.merge! attrs_arr
end

#organize_table_td(node) ⇒ Object



57
58
59
60
61
# File 'lib/plurimath/omml/parser.rb', line 57

def organize_table_td(node)
  node.locate("e/?").each do |child_node|
    child_node.name = "mtd" if child_node.name == "r"
  end
end

#parseObject



19
20
21
22
23
24
25
26
27
28
# File 'lib/plurimath/omml/parser.rb', line 19

def parse
  nodes = Ox.load(text, strip_namespace: true)
  @hash = { sequence: parse_nodes(nodes.nodes) }
  nodes = JSON.parse(@hash.to_json, symbolize_names: true)
  Math::Formula.new(
    Transform.new.apply(
      nodes,
    ),
  )
end

#parse_nodes(nodes) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/plurimath/omml/parser.rb', line 30

def parse_nodes(nodes)
  nodes.map do |node|
    if node.is_a?(String)
      node == "" ? nil : node
    elsif !node.attributes.empty?
      {
        node.name => {
          attributes: node.attributes,
          value: parse_nodes(node.nodes),
        },
      }
    else
      customize_tags(node) if CUSTOMIZABLE_TAGS.include?(node.name)
      { node.name => parse_nodes(node.nodes) }
    end
  end
end