委托给 class 变量
Delegate to class variable
我正在使用 Ruby 2.6.5 并尝试使用 def_delegator
委托给 class 变量。
class A
extend Forwardable
@@classB = B.new
def_delegator :@@classB, :method_name, :a_method_name
end
当我尝试做 A.new.a_method_name
时,我收到了 NameError (uninitialized class variable @@classB in Object)
。不确定我是否错误地调用了 def_delegator
,或者我是否只需要分解并使用 ActiveSupport 的 delegate
.
更新
根据可接受的答案,我的 class 定义如下所示:
class A
extend Forwardable
class << self
attr_accessor :classB
end
self.classB = B.new
def_delegator 'self.class.classB', :method_name, :a_method_name
end
你可以在class方法中初始化@@classB
,然后引用这个class方法:
class A
extend Forwardable
def self.b
@@classB ||= B.new
end
def_delegator 'self.class.b', :method_name, :a_method_name
end
我正在使用 Ruby 2.6.5 并尝试使用 def_delegator
委托给 class 变量。
class A
extend Forwardable
@@classB = B.new
def_delegator :@@classB, :method_name, :a_method_name
end
当我尝试做 A.new.a_method_name
时,我收到了 NameError (uninitialized class variable @@classB in Object)
。不确定我是否错误地调用了 def_delegator
,或者我是否只需要分解并使用 ActiveSupport 的 delegate
.
更新
根据可接受的答案,我的 class 定义如下所示:
class A
extend Forwardable
class << self
attr_accessor :classB
end
self.classB = B.new
def_delegator 'self.class.classB', :method_name, :a_method_name
end
你可以在class方法中初始化@@classB
,然后引用这个class方法:
class A
extend Forwardable
def self.b
@@classB ||= B.new
end
def_delegator 'self.class.b', :method_name, :a_method_name
end