Search code examples
rubydelegation

Delegate to class variable


I am using Ruby 2.6.5 and trying to use def_delegator to delegate to a class variable.

class A
  extend Forwardable

  @@classB = B.new
  def_delegator :@@classB, :method_name, :a_method_name
end

The is that when I try to do A.new.a_method_name I receive NameError (uninitialized class variable @@classB in Object). Not sure if I am making the call to def_delegator incorrectly or if I just need to break down and use ActiveSupport's delegate.

UPDATE

Based on acceptable answer my class definition looks like this:

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

Solution

  • You can initiaize @@classB inside a class method and then refer to this class method:

    class A
      extend Forwardable
    
      def self.b
        @@classB ||= B.new
      end
      def_delegator 'self.class.b', :method_name, :a_method_name
    end