有什么方法可以确定哪个对象调用了方法?
我希望 Ruby 的消息传递基础设施意味着可能有一些巧妙的技巧。
如何确定调用对象——哪个对象调用了我当前所在的方法?
I'm hoping that Ruby's message-passing infrastructure means there might be some clever trick for this.
How do I determine the calling object -- which object called the method I'm currently in?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以轻松查看调用感兴趣函数的代码行,通过
它会告诉您调用相关函数的文件名和行号。然后你可以反算出它是哪个对象。
然而,听起来您更喜欢调用某个函数的某个对象,也许是在实例方法中。我不知道有什么方法可以解决这个问题 - 但我无论如何都不会使用它,因为它似乎严重违反了封装。
You can easily look at the line of code that called the function of interest through
which will tell you the filename and line number which called the relevant function. You could then back-calculate which object it was.
However, it sounds like you're more after some object that called a certain function, perhaps within an instance method. I'm not aware of a method for figuring this out - but I wouldn't use it anyway, since it seems to violate encapsulation badly.
作为一个选项,有一个
binding_of_caller
gem 允许您在调用堆栈上任何调用者的上下文(调用者、调用者的调用者等)。它对于检查(阅读在调用堆栈上的任何位置执行任何操作)开发中的调用堆栈很有用,如better_errors
。我应该提一下,这种技术只能用于调试、娱乐或教育目的,因为它严重违反了 OOP 的原则。
主要是因为
eval
。让我们准备一些东西:
获取立即(堆栈上最接近的,因此
0
)调用者实例:...甚至是立即调用方法:
如果您需要更高的级别调用堆栈,使用
0
以外的数字来获取调用者的绑定。非常哈克。但如果你真的需要这个——就可以了。
As an option, there is a
binding_of_caller
gem that allows you to execute code in context of any caller on the call stack (caller, caller's caller and so on). It's useful for inspecting (read do anything at any position on the call stack) call stack in development, as used inbetter_errors
.Should I mention, this technique should only be used for debugging, fun or educational purposes, because it violates principles of OOP really badly.
Mostly because of
eval
.Let's prepare stuff:
Get the immediate (closest on stack, hence
0
) caller instance:...or even an immediate calling method:
If you need to get higher up the call stack, use numbers other than
0
for getting a caller's binding.Awfully hacky. But if you really need this — there you go.
最佳技术:
注意: 用于演示目的的线路号。
phone.rb:X
指线路X
脚本的。看看
phone.rb:13
!这个dial
方法就是发送呼叫的方法!而phone.rb:22
指的是使用dial
方法的鲁莽司机!Technology at its finest:
Note: Line number for demonstrative purposes.
phone.rb:X
refers to LineX
of the script.Look at
phone.rb:13
! Thisdial
method is what sent the call! Andphone.rb:22
refers to the reckless driver that used thedial
method!你的意思是像
self
?You mean like
self
?Peter 在生产代码示例中使用的 答案
在我的公司中,我们不推荐使用
deleted
标志,其风格为 < href="https://github.com/rubysherpas/paranoia" rel="nofollow noreferrer">Paranoia gemdeleted_at
列。下面的代码是我们在删除列之前确保一切顺利的方法(部署此代码,然后在上线 2 或 3 天后部署迁移remoove_column :lessons, :deleted
Peter's answer used in production code example
In my company we were deprecating
deleted
flag in flavor of Paranoia gemdeleted_at
column. The code bellow is how we were ensuring all will go well before we remove column (deploying this code and then after 2 or 3 days of being live we deploy migrationremoove_column :lessons, :deleted