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
- #treewalk(sexp = @sexp) ⇒ Object
- #xpath(path) ⇒ Object
Constructor Details
Instance Attribute Details
#doc ⇒ Object (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 |