Ruby on rails 如何在ruby中找到调用方类?
内部Ruby on rails 如何在ruby中找到调用方类?,ruby-on-rails,ruby,class,module,Ruby On Rails,Ruby,Class,Module,内部B#foo, 如何找到A类或任何其他参考或类名。 基本上它是从哪个类被称为 我试过这样的方法: class A def bar B.new.foo end end class B def foo #Here "HELLO WORLD!" end end A.new.bar 要获得整个堆栈,我通常会执行以下操作: self.class #B self.class.superclass #Object 其中,my_string是我项目的名称您是否
B#foo
,
如何找到A类
或任何其他参考或类名。
基本上它是从哪个类被称为
我试过这样的方法:
class A
def bar
B.new.foo
end
end
class B
def foo
#Here
"HELLO WORLD!"
end
end
A.new.bar
要获得整个堆栈,我通常会执行以下操作:
self.class
#B
self.class.superclass
#Object
其中,
my_string
是我项目的名称您是否尝试过调用方。first?尝试过,但它给出了调用方方法-/Users/vikas/Desktop/Test/friend.rb:31:in`bar'
caller.first-/Users/vikas/Desktop/Test/friend.rb:43:in`
这可能是您需要的答案。它使用一种涉及覆盖Class
的new
方法的方法来很好地跟踪类,可以通过定义foo
来缩小可能性:def foo;方法\u name=caller[0][/`\w+'/][1..-2];ObjectSpace.each_object(Class).选择{| c | c.instance_methods.include?(method_name)};结束
A.new.bar
导致method_name#=>:bar
并返回[A]
。如果其他类具有方法:bar
,则这些类将包含在a.new.bar
返回的数组中。如果你在家里尝试这个,你将需要取消上面的背景标记。(我躲开了它,好让人看见。)
caller.select {|x| x.include?("my_string") }