有没有办法从Rails控制台查看方法的源代码?

问题描述:

比方说,我有以下类:有没有办法从Rails控制台查看方法的源代码?

class User < ActiveRecord::Base 
    def fullname 
    "#{self.first_name} #{self.last_name}" 
    end 
end 

是否有可能对我来说,进入控制台,并查看全名法的源码输出在控制台不知何故?像,它看起来像...

irb(main):010:0> omg_console_you_are_awesome_show_source(User.fullname) 
[Fri Jun 29 14:11:31 -0400 2012] => def fullname 
[Fri Jun 29 14:11:31 -0400 2012] => "#{self.first_name} #{self.last_name}" 
[Fri Jun 29 14:11:31 -0400 2012] => end 

或者真的有什么方法可以查看源代码?谢谢!

+0

https://github.com/banister/method_source – carlosvini

你也可以使用pry (http://pry.github.com/)这就像IRB类固醇。你可以做的东西,如:

[1] pry(main)> show-source Array#each 

From: array.c in Ruby Core (C Method): 
Number of lines: 11 
Owner: Array 
Visibility: public 

VALUE 
rb_ary_each(VALUE ary) 
{ 
    long i; 

    RETURN_ENUMERATOR(ary, 0, 0); 
    for (i=0; i<RARRAY_LEN(ary); i++) { 
    rb_yield(RARRAY_PTR(ary)[i]); 
    } 
    return ary; 
} 
[2] pry(main)> show-doc Array#each 

From: array.c in Ruby Core (C Method): 
Number of lines: 11 
Owner: Array 
Visibility: public 
Signature: each() 

Calls block once for each element in self, passing that 
element as a parameter. 

If no block is given, an enumerator is returned instead. 

    a = [ "a", "b", "c" ] 
    a.each {|x| print x, " -- " } 

produces: 

    a -- b -- c -- 
+0

哇,永远不会知道这一点。真棒。 – dojosto

不正是你在问什么,但这Railscast可能会有所帮助。

它教你一个技巧,可以让你从Rails控制台打开文本编辑器中的方法。

UPDATE:

我才意识到那个链接是付费墙...这里的技巧的总结。

添加到您的〜/ .irbrc文件

class Object 
    def mate(method_name) 
    file, line = method(method_name).source_location 
    `mate '#{file}' -l #{line}` 
    end 
end 

...这里的队友是CLI命令打开TextMate的(当然subl的这里可以用于崇高文本)。

然后在控制台只需调用

helper.mate(:number_to_currency) 

...其中number_to_currency是谁是您要查看源的方法。

顺便说一句,如果你还没有,你应该订阅Railscast Pro。海事组织,没有更好的方式每月花费9美元。并且要透露,我与该网站没有任何关系,除非是满意的客户。

+0

撬的办法是冷却器;) – horseyguy

+0

同意。撬更酷了。 :) –