如何在Ruby中检索调用者上下文对象? [英] How to retrieve caller context object in Ruby?

查看:84
本文介绍了如何在Ruby中检索调用者上下文对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此后是我想简化的代码段,以避免在每次调用时传递额外的参数.实际上,我的用例是M是一个用户库,在每个方法上都没有定义context参数. check是用户未定义的方法.

hereafter is my piece of code that I want to simplify in order to avoid passing an extra argument on each call. In fact, my usecase is that M is a user library without the definition of context argument on each method. check is a method that is not defined by the user.

# User code
module M
  def do_something(context)
    puts "Called from #{context}"
    context.check
  end
  module_function :do_something
end

# Application code
class Bar
  def check
    puts "Checking from #{self}..."
  end
end

class Foo < Bar
  def do_stuff(scope, method)
    scope.send method, self
  end
end

# Executed by user
Foo.new.do_stuff M, :do_something

是否有一种方法可以做同样的思考而无需将self作为输入参数传递给do_something方法以检索check方法?

Is there a way to do the same think without passing self as an input argument to do_something method in order to retrieve check method ?

# User code
module M
  def do_something
    called_from_object = ???
    puts "Called from #{called_from_object}"
    called_from_object.check
  end
  module_function :do_something
end

# Application code
class Bar
  def check
    puts "Checking from #{self}..."
  end
end

class Foo < Bar
  def do_stuff(scope, method)
    scope.send methood
  end
end

# Executed by user
Foo.new.do_stuff M, :do_something

感谢您的支持!

推荐答案

在为我自己的目的寻找答案的同时,也喜欢这篇文章.

Came across this post while looking for an answer for my own purposes.

找不到合适的扩展程序,因此我翻阅了Ruby源代码并整理了一个扩展.我已经将其捆绑为gem-只要您使用的是Ruby 1.9.1,就可以毫无问题地安装它:

Didn't find one that was appropriate, so I dug through the Ruby source and put together an extension. I've bundled it as a gem- should install without any problem so long as you are using Ruby 1.9.1:

sudo gem安装发件人

sudo gem install sender

不适用于Ruby 1.8,因为1.8具有用于跟踪帧的不同模型.

This will not work with Ruby 1.8, as 1.8 has a different model for tracking frames.

http://rubygems.org/gems/sender

这篇关于如何在Ruby中检索调用者上下文对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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