我可以使用 Pry 获取类的源代码。
[1] pry(main)> class AAA
[1] pry(main)* def aaa
[1] pry(main)* "111"
[1] pry(main)* end
[1] pry(main)* end
=> nil
[2] pry(main)> Pry.WrappedModule(AAA).source
=> "class AAA\n def aaa\n \"111\"\n end\nend\n"
[3] pry(main)>
是否可以通过动态添加的方法获取对象的源代码?我尝试了一些,但我无法获得来源。
[1] pry(main)> class AAA
[1] pry(main)* end
=> nil
[2] pry(main)> a = AAA.new
=> #<AAA:0x007fe3de0c0570>
[3] pry(main)> cd a
[4] pry(#<AAA>):1> def aaa
[4] pry(#<AAA>):1* "111"
[4] pry(#<AAA>):1* end
=> nil
[5] pry(#<AAA>):1> cd ..
[6] pry(main)> Pry.WrappedModule(a)
ArgumentError: Tried to initialize a WrappedModule with a non-module #<AAA:0x007fe3de0c0570>
from /usr/local/Cellar/ruby/2.0.0-p247/lib/ruby/gems/2.0.0/gems/pry-0.9.12.2/lib/pry/wrapped_module.rb:59:in `initialize'
[7] pry(main)> Pry.WrappedModule(a).source
ArgumentError: Tried to initialize a WrappedModule with a non-module #<AAA:0x007fe3de0c0570>
from /usr/local/Cellar/ruby/2.0.0-p247/lib/ruby/gems/2.0.0/gems/pry-0.9.12.2/lib/pry/wrapped_module.rb:59:in `initialize'
[8] pry(main)> Pry.WrappedModule(AAA)
=> #<Pry::WrappedModule:0x007fe3dd938820
@doc=nil,
@host_file_lines=nil,
@memoized_candidates=[],
@source=nil,
@source_location=nil,
@wrapped=AAA>
[9] pry(main)>