Class: RecentRuby::XMLAST
- Inherits:
-
Object
- Object
- RecentRuby::XMLAST
- Includes:
- REXML
- Defined in:
- lib/recent_ruby/xml_ast.rb
Overview
Class comes from: medium.com/rubyinside/using-xpath-to-rewrite-ruby-code-with-ease-8f635af65b5b TODO: turn into a separate gem
Instance Attribute Summary collapse
-
#doc ⇒ Object
readonly
Returns the value of attribute doc.
Instance Method Summary collapse
-
#initialize(sexp) ⇒ XMLAST
constructor
A new instance of XMLAST.
- #populate_tree(xml, sexp) ⇒ Object
- #pp ⇒ Object
- #treewalk(sexp = @sexp) ⇒ Object
- #xpath(path) ⇒ Object
Constructor Details
Instance Attribute Details
#doc ⇒ Object (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 |
#pp ⇒ Object
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 |