【问题标题】:Is there something similar to Nokogiri for parsing Ruby code?有没有类似于 Nokogiri 的东西来解析 Ruby 代码?
【发布时间】:2011-09-16 19:21:33
【问题描述】:

Nokogiri 很棒。我可以执行#css('.bla') 之类的操作,它将返回第一个匹配元素。

现在我们需要对 Ruby 源代码进行一些解析 - 查找类中的所有方法等。我们正在使用 ruby_parser gem,但它所做的只是梳理您的源代码并吐出 S 表达式。对于这些 S 表达式,是否有类似 Nokogiri 的东西可以执行诸如“为找到的名为 'foo' 的第一个方法返回 S 表达式”之类的事情?

【问题讨论】:

  • 你真的需要解析它吗?正如 nash 提到的,Ruby 元编程没有什么不能做的。
  • 即使你可以,也不会告诉你任何动态定义的方法,例如define_method("foo_#{bar}")

标签: ruby parsing nokogiri s-expression


【解决方案1】:

你可以检查 rubinius 解析器,它可以帮助你做你想做的事。

【讨论】:

    【解决方案2】:

    虽然我接受 Jörg 的回答是因为它更完整,但我最终发现了我最终使用的其他东西。 ruby_parser 安装了一个名为sexp_processor 的依赖gem(它在这个gem 中实际定义了Sexp 类)。如果您查看class docs,有一些方法将有助于基本的 Ruby 查找器。这是一个例子:

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

    【讨论】:

      【解决方案3】:

      我唯一能想到的就是Adam Sanderson's SExpPath library

      【讨论】:

        【解决方案4】:

        我对您正在寻找的 gem 一无所知,但您可以使用 instance_methods 找到类中的所有方法:

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

        【讨论】:

          猜你喜欢
          • 2012-01-30
          • 1970-01-01
          • 2016-03-16
          • 2014-12-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-11
          • 1970-01-01
          相关资源
          最近更新 更多