Is there something similar to Nokogiri for parsing Ruby code?

允我心安 提交于 2019-12-04 03:57:27

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

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
  }
}

I don't know anything about gem that you are looking for, but you can find all methods within a class using instance_methods:

class Foo
  def bar
  end
end

irb(main):005:0> Foo.instance_methods - Object.instance_methods
=> [:bar]
Schmurfy

You could check the rubinius parser, it may help you to do what you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!