我们最近遇到了一个问题,即在进行了一系列提交之后,后端进程无法运行。现在,我们是好 child ,每次登录后都运行rake test
,但是由于Rails库加载的奇怪之处,只有在我们以生产模式直接从Mongrel运行时才发生。
我跟踪了该错误,原因是新的Rails gem覆盖了String类中的一种方法,从而打破了运行时Rails代码中的一种狭义用法。
总之,长话短说,在运行时是否有办法询问Ruby在哪里定义了方法?类似于whereami( :foo )
的返回/path/to/some/file.rb line #45
的东西?在这种情况下,告诉我它在String类中定义是没有帮助的,因为它已被某些库重载。
我不能保证源代码存在于我的项目中,因此对'def foo'
进行grepping并不一定能满足我的需要,更不用说我是否有许多def foo
,有时我直到运行时才知道可能使用的是哪个。
最佳答案
这确实很晚,但是您可以通过以下方法找到方法的定义位置:
http://gist.github.com/76951
# How to find out where a method comes from.
# Learned this from Dave Thomas while teaching Advanced Ruby Studio
# Makes the case for separating method definitions into
# modules, especially when enhancing built-in classes.
module Perpetrator
def crime
end
end
class Fixnum
include Perpetrator
end
p 2.method(:crime) # The "2" here is an instance of Fixnum.
#<Method: Fixnum(Perpetrator)#crime>
如果您使用的是Ruby 1.9+,则可以使用
source_location
require 'csv'
p CSV.new('string').method(:flock)
# => #<Method: CSV#flock>
CSV.new('string').method(:flock).source_location
# => ["/path/to/ruby/1.9.2-p290/lib/ruby/1.9.1/forwardable.rb", 180]
请注意,这不适用于所有内容,例如 native 编译代码。 Method class也具有一些简洁的功能,例如Method#owner,它返回定义方法的文件。
编辑:在其他答案中也请参见
__file__
和__line__
和REE注释,它们也很方便。 -wg