问题描述
我在程序上设置了一些跟踪代码,并且想知道哪些方法是通过attr_accessor
定义的.使用TracePoint
,我可以检测到何时调用attr_accessor
,但是我不知道如何获取它来告诉我所接收到的参数.有任何想法吗?
I am setting some trace code on my program, and would like to know which methods are defined through attr_accessor
. Using TracePoint
, I can detect when attr_accessor
is called, but I don't know how to get it to tell me the arguments it received. Any ideas?
推荐答案
在问题标题中,您要求提供一个变量列表,但这回答了问题正文,该问题要求提供了所定义方法的列表.
In the question title, you asked for a list of variables, but this answers the question body, which asked for a list of the methods defined.
此方法不会打扰检查实例变量,如果您开始手动更新或创建其他实例变量,则会引入噪音.
This method doesn't bother checking instance variables, which will have noise introduced if you begin manually updating or creating other instance variables.
module MethodTracer
TracePoint.trace(:c_call) do |t|
if (t.method_id == :attr_accessor)
t.self.extend(MethodTracer)
methods = t.self::Methods ||= []
MethodTracer.send(:define_method, :method_added) {|m| methods << m }
end
end
TracePoint.trace(:c_return) do |t|
if (t.method_id == :attr_accessor)
MethodTracer.send(:remove_method, :method_added)
end
end
end
class Foo
attr_accessor :a, :b
attr_accessor :c
def foo; end
end
Foo::Methods # => [:a, :a=, :b, :b=, :c, :c=]
我已经将方法名称存储在Methods
常量中,但是显然,您可以将它们存储在最方便的位置.
I've stored the method names in the Methods
constant, but obviously you can store them wherever is most convenient for you.
在MethodTracer
上定义/删除method_added
可确保您不会破坏自己定义的任何Foo.method_added
.但是,此方法确实要求,如果在调用attr_accessor
之前定义了Foo.method_added
,则需要在其中调用super
.否则,您将跳过由MethodTracer
定义的临时method_added
.
Defining/removing method_added
on MethodTracer
ensures that you don't clobber any Foo.method_added
you've defined yourself. This methodology, however, does require that if you define Foo.method_added
before your calls to attr_accessor
, you will need to call super
inside it. Otherwise you will skip the temporary method_added
defined by MethodTracer
.
这篇关于获取通过"attr_accessor"定义的所有变量,而不覆盖"attr_accessor"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!