有什么方法可以确定哪个对象称为方法? [英] Any way to determine which object called a method?

查看:95
本文介绍了有什么方法可以确定哪个对象称为方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望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?

推荐答案

作为选择,还有一个 binding_of_caller gem ,可让您在调用堆栈上的任何调用者(调用者,调用者的调用者等)的上下文中执行代码.它对于检查开发中的调用栈(在调用栈中的任何位置读取 )非常有用,如 better_errors .

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 in better_errors.

Binding的对象将执行上下文封装在代码中的某些特定位置,并保留此上下文以供将来使用.

Objects of class Binding encapsulate the execution context at some particular place in the code and retain this context for future use.

http://www.ruby-doc.org/core-2.1.4 /Binding.html

我应该提到,该技术只能用于调试,娱乐或教育目的,因为它确实严重违反了OOP原则.
主要是因为eval.

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.

让我们准备东西:

require 'binding_of_caller' # I assume, you installed this gem already?

获取立即(堆栈上最近,因此为0)调用方实例:

Get the immediate (closest on stack, hence 0) caller instance:

binding.of_caller(0).eval('self')

...甚至是直接调用方法:

...or even an immediate calling method:

binding.of_caller(0).eval('__method__')

如果需要使调用堆栈更高级,请使用0以外的数字来获取呼叫者的绑定.

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.

这篇关于有什么方法可以确定哪个对象称为方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆