如果我在 IRB 中定义了一个方法,有什么方法可以在稍后的会话中查看其源代码吗?
> def my_method
> puts "hi"
> end
稍后输出几个屏幕我希望能够写出类似的东西
> source my_method
然后回来:
=> def my_method; puts "hi"; end;
这可能吗?
不是在 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)>
如果您使用 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"
编辑:另请查看method_source,这是 pry 内部使用的。
我使用的是method_source我有方法code,它基本上是我对这个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
用法是:
code Foo, :bar
或实例
code foo_instance, :bar
更好的方法是在 /lib 文件夹中使用你的 irb 扩展名,而不是仅仅在初始化程序之一中 require 它(或创建你自己的)
在irb v1.3.5之后,irb本身实现了
show_source
及其别名$
。您可以显示如下方法定义。
irb(main):001> IRB::VERSION
=> "1.12.0"
irb(main):002* def foo
irb(main):003* puts "hi"
irb(main):004> end
=> :foo
irb(main):005> show_source foo
From: (irb):2
def foo
puts "hi"
end
=> nil
irb(main):006> $ foo
From: (irb):2
def foo
puts "hi"
end
=> nil
irb(main):007> # For instance methods
=> nil
irb(main):008* class A
irb(main):009* def bar
irb(main):010* puts "hello from A"
irb(main):011* end
irb(main):012> end
=> :bar
irb(main):013* class B < A
irb(main):014* def bar
irb(main):015* puts "hello from B"
irb(main):016* super
irb(main):017* end
irb(main):018> end
=> :bar
irb(main):019> $ B#bar
From: (irb):14
def bar
puts "hello from B"
super
end
=> nil
irb(main):020> $ B#bar --super
From: (irb):9
def bar
puts "hello from A"
end
=> nil