Sha256: cbbca85a7f281b09bf679b7d471f7c92d130be996ed900d12ebdfabb3a5047f4

Contents?: true

Size: 1.41 KB

Versions: 5

Compression:

Stored size: 1.41 KB

Contents

# frozen_string_literal: true

require 'parser/current'
require 'rexml/document'

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

  class XMLAST
    include REXML
    attr_reader :doc

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

    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

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

    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

    def pp
      doc.write(STDOUT, 2)
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
recent_ruby-0.1.5 lib/recent_ruby/xml_ast.rb
recent_ruby-0.1.4 lib/recent_ruby/xml_ast.rb
recent_ruby-0.1.3 lib/recent_ruby/xml_ast.rb
recent_ruby-0.1.2 lib/recent_ruby/xml_ast.rb
recent_ruby-0.1.1 lib/recent_ruby/xml_ast.rb