【问题标题】:Access Pry's show-source method from Ruby file从 Ruby 文件访问 Pry 的 show-source 方法
【发布时间】:2019-01-07 13:16:58
【问题描述】:

是否可以从 Ruby 文件中访问 Pry 的 show-source 方法?如果是这样,这是怎么做的?

例如,如果我有这个文件:

# testing.rb

require 'pry' 

def testing
  puts 'hi'
end

puts show-source testing

然后运行ruby testing.rb,我想要输出:

Owner: testing.rb
Visibility: public
Number of lines: 3

def testing
  puts 'hi'
end

为了解释这一点,我有一个对方法进行存根的测试,尽管原始方法似乎偶尔会被调用,我认为输出调用的源以查看它的来源会很方便。我知道有更简单的方法可以做到这一点,尽管从这个兔子洞开始并且有兴趣看看这是否可以做到:)

运行稍微有点头疼的show-source show-source 会显示Pry::Command::ShowSource 类中的一些方法,该类继承自Pry::Command::ShowInfo

Pry::Command::ShowSource 显示了三个方法:optionsprocesscontent_for,尽管我无法成功调用任何方法。

我最好的假设是 content_for 方法处理这个问题,使用从父类分配的代码对象(即Pry::CodeObject.lookup(obj_name, _pry_, :super => opts[:super])),尽管我无法破解这个问题。

有人对此有任何想法或示例吗?

【问题讨论】:

    标签: ruby-on-rails ruby pry


    【解决方案1】:

    Ruby 具有内置方法Method#source_location,可用于查找源的位置。 method_source gem 以此为基础,根据源位置提取源。但是,这不适用于交互式控制台中定义的方法。方法必须在文件中定义。

    这是一个例子:

    require 'set'
    require 'method_source'
    
    puts Set.method(:[]).source_location
    # /home/user/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/set.rb
    # 74
    #=> nil
    
    puts Set.method(:[]).source
    # def self.[](*ary)
    #   new(ary)
    # end
    #=> nil
    

    请记住,所有核心 Ruby 方法都是用 C 编写的,并返回 nil 作为源位置。 1.method(:+).source_location #=> nil 标准库是用 Ruby 本身编写的。因此,上面的示例适用于 Set 方法。

    【讨论】:

    • 完美 - 谢谢@JohanWentholt。这完全符合我的追求。欣赏答案。
    【解决方案2】:

    您可以在不使用 pryObject#methodMethod#source_location 的情况下访问方法的源代码,如以下答案所述:https://stackoverflow.com/a/46966145/580346

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-28
      • 1970-01-01
      • 2016-04-18
      • 1970-01-01
      相关资源
      最近更新 更多