我正在使用一个基本对象代理,我需要检测我是否传递了一个实际的对象或这样的代理。问题是没有定义is_a?
或class
等方法
module ControllerProxyable
extend ActiveSupport::Concern
included do
attr_reader :controller
delegate :current_user, to: :controller
end
def controller_proxy(controller)
# is_a? actually is NOT defined for a BasicObject causes the following to crash
@controller = if controller.is_a?(ControllerProxy)
controller
else
ControllerProxy.new(controller)
end
end
end
class ControllerProxy < BasicObject
def initialize(controller = nil)
@controller = controller
end
def some_proxy_method
end
# def respond_to and respond_to_missing not relevant here
end
这是我如何使用它的一个例子:
class Foo
include ControllerProxyable
def initialize(controller: nil)
controller_proxy(controller)
end
def bar
bar ||= Bar.new(controller: controller)
end
end
class Bar
include ControllerProxyable
def initialize(controller: nil)
controller_proxy(controller)
end
end
因此,以下内容不起作用
Foo.new(controller: nil).bar.some_proxy_method
如何为代理定义is_a?
(或实际标识我正在使用代理)?
3条答案
按热度按时间ldfqzlk81#
问题是没有定义
is_a?
或class
等方法对于“某些方法没有定义”的问题,最明显的解决方案是定义方法:
但是!这违背了代理的全部目的,即与真实的东西无法区分。更好的方法是IMO:
hujrc8aj2#
我其实找到了RUby 2 here的答案。我的问题几乎感觉像是重复,但在我的情况下,我谈论的是basicObject类的扩展,而不是修补BasicObject类本身
对于这样的用例,这变为:
vptzau2j3#
可以识别一个代理来转发所有带有
===
的方法:下面是我如何识别AR模型的
Octopus::ScopeProxy
Package 器的示例: