Class: RecentRuby::XMLAST

Inherits:
Object
  • Object
show all
Includes:
REXML
Defined in:
lib/recent_ruby/xml_ast.rb

Overview

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sexp) ⇒ XMLAST

Returns a new instance of XMLAST.



14
15
16
17
18
19
# File 'lib/recent_ruby/xml_ast.rb', line 14

def initialize(sexp)
  @doc = Document.new '<root></root>'
  @sexp = sexp
  root = @doc.root
  populate_tree(root, sexp)
end

Instance Attribute Details

#docObject (readonly)

Returns the value of attribute doc.



12
13
14
# File 'lib/recent_ruby/xml_ast.rb', line 12

def doc
  @doc
end

Instance Method Details

#populate_tree(xml, sexp) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/recent_ruby/xml_ast.rb', line 21

def populate_tree(xml, sexp)
  if sexp.is_a?(String) ||
     sexp.is_a?(Symbol) ||
     sexp.is_a?(Numeric) ||
     sexp.is_a?(NilClass)
    el = Element.new(sexp.class.to_s.downcase + '-val')
    el.add_attribute 'value', sexp.to_s
    xml.add_element el
  else
    el = Element.new(sexp.type.to_s)
    el.add_attribute('id', sexp.object_id)

    sexp.children.each { |n| populate_tree(el, n) }
    xml.add_element el
  end
end

#ppObject



56
57
58
# File 'lib/recent_ruby/xml_ast.rb', line 56

def pp
  doc.write(STDOUT, 2)
end

#treewalk(sexp = @sexp) ⇒ Object



38
39
40
41
# File 'lib/recent_ruby/xml_ast.rb', line 38

def treewalk(sexp = @sexp)
  return sexp unless sexp&.respond_to?(:children)
  [sexp, sexp.children.map { |n| treewalk(n) }].flatten
end

#xpath(path) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/recent_ruby/xml_ast.rb', line 43

def xpath(path)
  results = XPath.match(doc, path)
  results.map do |n|
    if n.respond_to?(:attributes) && n.attributes['id']
      treewalk.find do |m|
        m.object_id.to_s == n.attributes['id']
      end
    else
      n
    end
  end
end