2011-08-25 3 views
12

IRBでメソッドを定義した場合、セッションの後半でそのソースを確認する方法はありますか?IRBでは、前に定義した方法のソースを確認できますか?

=> def my_method; puts "hi"; end; 

はこれが可能である:出力の

> def my_method 
> puts "hi" 
> end 

複数の画面後、私は

> source my_method 

ような何かを書くことができるようにして戻って取得したいのですが?

答えて

13

Try pry。それについてrailscastがあります(この同じ週にリリースされました!)、show-methodを使用してコードを表示する方法を示します。

5

あなたはRubygems.org上のRuby 1.9.2と利用可能なよりsourcify宝石の新しいバージョンを使用している場合(例えば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" 

編集:もチェックをout method_source、これは内部で使用されるものです。

+0

これは私にとっては役に立たない – horseyguy

+1

私が言ったように、Ruby 1.9.2とRubygems.org(Gitリポジトリから鉱山を作りました)で現在入手可能なものよりも新しい 'sourcify'のバージョンが必要です。これをもっと明確にするために投稿を更新しました。 –

13

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

私は何を使用すると、私は基本的にこの宝石のための私のラッパーである方法コードを持ってmethod_sourceです。 Railsアプリケーション用のGemfileに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 

より良いアプローチは、あなただけのそれを必要とするよりも、あなたのIRB拡張子を持つ/ libフォルダに持つクラスを持つことですイニシャライザの1つで(または自分で作成する)

関連する問題