如果我在IRB中定义一个方法,有没有办法在会话后期查看其来源?
> def my_method
> puts "hi"
> end
Run Code Online (Sandbox Code Playgroud)
几个输出屏幕后来我希望能够写出像
> source my_method
Run Code Online (Sandbox Code Playgroud)
并回来:
=> def my_method; puts "hi"; end;
Run Code Online (Sandbox Code Playgroud)
这可能吗?
hor*_*guy 14
不在IRB中,但在Pry中,此功能是内置的.
看吧:
pry(main)> def hello
pry(main)* puts "hello my friend, it's a strange world we live in"
pry(main)* puts "yes! the rich give their mistresses tiny, illuminated dying things"
pry(main)* puts "and life is neither sacred, nor noble, nor good"
pry(main)* end
=> nil
pry(main)> show-method hello
From: (pry) @ line 1:
Number of lines: 5
def hello
puts "hello my friend, it's a strange world we live in"
puts "yes! the rich give their mistresses tiny, illuminated dying things"
puts "and life is neither sacred, nor noble, nor good"
end
pry(main)>
Run Code Online (Sandbox Code Playgroud)
如果您使用Ruby 1.9.2以及比Rubygems.org上提供的更新版本的sourcify gem(例如从GitHub构建源代码),您可以这样做:
>> require 'sourcify'
=> true
>>
.. class MyMath
.. def self.sum(x, y)
.. x + y # (blah)
.. end
.. end
=> nil
>>
.. MyMath.method(:sum).to_source
=> "def sum(x, y)\n (x + y)\nend"
>> MyMath.method(:sum).to_raw_source
=> "def sum(x, y)\n x + y # (blah)\n end"
Run Code Online (Sandbox Code Playgroud)
编辑:还要检查出method_source,这是pry在内部使用的内容.
我使用的是method_source我有方法代码,它基本上是我对这个 gem 的包装。在 Gemfile for Rails 应用程序中添加 method_source 。并使用以下代码创建初始化程序。
# Takes instance/class, method and displays source code and comments
def code(ints_or_clazz, method)
method = method.to_sym
clazz = ints_or_clazz.is_a?(Class) ? ints_or_clazz : ints_or_clazz.class
puts "** Comments: "
clazz.instance_method(method).comment.display
puts "** Source:"
clazz.instance_method(method).source.display
end
Run Code Online (Sandbox Code Playgroud)
用法是:
code Foo, :bar
Run Code Online (Sandbox Code Playgroud)
或实例
code foo_instance, :bar
Run Code Online (Sandbox Code Playgroud)
更好的方法是在 /lib 文件夹中包含带有 irb 扩展名的类,而不是只在初始化程序之一中需要它(或创建自己的初始化程序)