Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something similar to Nokogiri for parsing Ruby code?

Nokogiri is awesome. I can do things like #css('.bla') which will return the first matching element.

Right now we need to do some parsing of Ruby source code - finding all methods within a class etc. We're using the ruby_parser gem, but all it does is comb your source code and spit out S-expressions. Is there anything like Nokogiri for these S-expressions which can do things like "return S-expression for first method found named 'foo'"?

like image 575
Suan Avatar asked Jun 16 '11 23:06

Suan


2 Answers

The only thing I can think of, is Adam Sanderson's SExpPath library.

like image 113
Jörg W Mittag Avatar answered Nov 17 '22 16:11

Jörg W Mittag


Although I am accepting Jörg's answer because it is more complete, I ended up discovering something else which I ended up using. ruby_parser installs a dependent gem named sexp_processor (it is in this gem where the Sexp class is actually defined). If you view the class docs there are a few methods that will help with basic Ruby finders. Here's an example:

class Sexp
  def name          # convenience method
    self.sexp_body.first
  end
end    

# Print out all instance methods within classes. Beware - if "code" sexp itself
# is a class, it will NOT be included!
code = RubyParser.new.parse(IO.read('/src/file'))
code.each_of_type(:class){ |klass|
  klass.each_of_type(:defn){ |meth|
    puts meth.name
  }
}
like image 33
Suan Avatar answered Nov 17 '22 15:11

Suan