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.



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

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.



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

def doc
  @doc
end

Instance Method Details

#populate_tree(xml, sexp) ⇒ Object



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

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

#treewalk(sexp = @sexp) ⇒ Object



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

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

#xpath(path) ⇒ Object



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

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