In IRB, can I view the source of a method I defined earlier?

这一生的挚爱 提交于 2019-12-04 00:51:58
Serabe

Try pry. There is a railscast about it (released this same week!) and it shows you how to show the code by using show-method.

Not in IRB but in Pry this feature is built-in.

Behold:

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

If you use Ruby 1.9.2 and a newer version of the sourcify gem than available on Rubygems.org (e.g. build the source from GitHub), you can do this:

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

Edit: also check out method_source, which is what pry uses internally.

What I use is method_source I have method code which is basically my wrapper for this gem. Add method_source in Gemfile for Rails apps. And create initializer with following code.

  # 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

Usage is:

code Foo, :bar

or with instance

code foo_instance, :bar

Better approach is to have class with in /lib folder with your irb extension, than you just require it in one of initializers (or create your own)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!