class RecentRuby::XMLAST

Class comes from: medium.com/rubyinside/using-xpath-to-rewrite-ruby-code-with-ease-8f635af65b5b TODO: turn into a separate gem

Attributes

doc[R]

Public Class Methods

new(sexp) click to toggle source
# 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

Public Instance Methods

populate_tree(xml, sexp) click to toggle source
# 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
pp() click to toggle source
# File lib/recent_ruby/xml_ast.rb, line 56
def pp
  doc.write(STDOUT, 2)
end
treewalk(sexp = @sexp) click to toggle source
# 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) click to toggle source
# 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