gpt4 book ai didi

ruby - 使用来自另一个类的另一个实例的方法扩展一个实例

转载 作者:数据小太阳 更新时间:2023-10-29 08:08:11 24 4
gpt4 key购买 nike

目前我正在做类似下面的事情来让 Runnable 类的 run 方法访问 ExecutionContext 方法:

class ExecutionContext
def message(text)
puts "ExecutionContext.message: #{text}"
end
def answer?
puts "ExecutionContext.answer called"
true
end
end

class Controller
def do_run(context)
@context = context
run
@context = nil
end

def method_missing(mth, *args)
@context.send(mth, *args)
end
end

class Runnable < Controller
def run
if answer?
message "Runnable's block executing!"
end
end
end

runnable = Runnable.new

context = ExecutionContext.new
runnable.do_run(context)

想法是 Runnable 类是由想要访问功能的“最终用户”编写的(例如 messageanswer? 方法)从别处提供的 ExecutionContext 实例。事实上,Runnable 类是“最终用户”所关心的,它应该尽可能小和简单。

上面的代码按预期工作,因为 Runnable.run 调用的所有方法都是由 ExecutionContext 提供的。

但是我想知道是否有更优雅的方法来实现同样的事情,我可以避免使用 method_missing 和定义临时 @context 实例变量。

理想情况下,我想将代码修改为与此类似的内容(ExecutionContext 保持不变):

class Controller
def do_run(context, runnable)
runnable.extend_from_instance(context)
runnable.run
end
end

class Runnable
def run
if answer?
message "Runnable's block executing!"
end
end
end

runnable = Runnable.new
context = ExecutionContext.new
Controller.new.do_run(context, runnable)

extend_from_instance这样的东西吗?

更新

感谢大家的关注。

由于它出现在我目前得到的两个答案中,我意识到我应该提到以下限制:不幸的是 RunnableExecutionContext 都不能变成 模块。它们需要是 classes,因为它们的实例在不同情况下会有不同的行为(两者都有自己的实例变量等)。

我真的需要 run 方法来执行,就好像它是 ExecutionContext instance 的一部分一样(context在代码中)。

最佳答案

是的,在这种情况下您不想使用method_missing

我真的不明白你想要完成什么。也许 define_block 不是正确的名称...?

但是,模块似乎具有您想要的功能。

module Messaging
def message(text)
puts "Provider.message: #{text}"
end
end

class Parent
include Messaging
...

编辑:我想你想使用绑定(bind)。它允许您将当前范围(上下文)传递到另一个范围。

def print_local binding
puts 'local is ' + binding.eval('local')
end

def foo
local = 'value'
print_local binding
end

foo
=> local is value

在这种情况下,print_local 想要打印 foo 的 local 变量。但它无法访问它,因为 local 仅存在于 foo 的范围(或上下文)中。

因此,您可以将 foo 的作用域作为 binding 传递。

参见 binding .

关于ruby - 使用来自另一个类的另一个实例的方法扩展一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30089687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com