Class: Plurimath::Omml::Parser

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

Constant Summary collapse

CUSTOMIZABLE_TAGS =
%w[
  eqArr
  sPre
  mr
  r
].freeze
SUPPORTED_FONTS =
{
  "sans-serif-bi": "sans-serif-bold-italic",
  "double-struck": "double-struck",
  "sans-serif-i": "sans-serif-italic",
  "sans-serif-b": "bold-sans-serif",
  "sans-serif-p": "sans-serif",
  "fraktur-p": "fraktur",
  "fraktur-b": "bold-fraktur",
  "script-b": "bold-script",
  "script-p": "script",
  monospace: "monospace",
  bi: "bold-italic",
  p: "normal",
  i: "italic",
  b: "bold",
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text) ⇒ Parser

Returns a new instance of Parser.



32
33
34
# File 'lib/plurimath/omml/parser.rb', line 32

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



65
66
67
68
69
70
71
72
73
74
# File 'lib/plurimath/omml/parser.rb', line 65

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

#organize_fonts(node) ⇒ Object



82
83
84
85
86
87
88
# File 'lib/plurimath/omml/parser.rb', line 82

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

#organize_spre(node) ⇒ Object



90
91
92
93
# File 'lib/plurimath/omml/parser.rb', line 90

def organize_spre(node)
  node.locate("sub").first.name = "sPreSub"
  node.locate("sup").first.name = "sPreSup"
end

#organize_table_td(node) ⇒ Object



76
77
78
79
80
# File 'lib/plurimath/omml/parser.rb', line 76

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

#parseObject



36
37
38
39
40
41
42
43
44
45
# File 'lib/plurimath/omml/parser.rb', line 36

def parse
  nodes = Plurimath.xml_engine.load(text)
  @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



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/plurimath/omml/parser.rb', line 47

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