繁体   English   中英

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

[英]Is there a way to view a method's source code from the Rails console?

假设我有以下课程:

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

我是否可以进入控制台并以某种方式在控制台中查看fullname方法的源代码输出? 就像,它看起来像......

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

或者真的以任何方式查看源代码? 谢谢!

你也可以使用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 --

不完全是你在问什么,但这个Railscast可能有所帮助。

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

更新:

我刚刚意识到链接是付费墙背后的...这是诀窍的总结。

将其添加到〜/ .irbrc文件中

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

...其中mate是打开TextMate的CLI命令(当然subl可以在这里用于Sublime Text)。

然后在控制台中简单地调用

helper.mate(:number_to_currency)

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

顺便说一句,如果你还没有,你应该订阅Railscast Pro IMO,没有更好的方法每月花9美元。 并且要透露,我与该网站没有任何关系,然后是满意的客户。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM