Search code examples
rubyprotectedsuperclassclass-method

Calling a Protected Superclass Class Method in Ruby


I want to call a protected superclass class method from an instance method in the base class.

class A
  class << self
    protected
    def foo
      puts "In foo"
    end
  end
end

class B < A
  def bar
    puts "In bar"
    # call A::foo
  end
end

What's the best way to do this?


Solution

  • Override the method in B, calling super:

    class A
      class << self
        protected
        def foo
          puts "In foo"
        end
      end
    end
    
    class B < A
    
      def self.foo
        super
      end
    
      def bar
        puts "In bar"
        # call A::foo
        self.class.foo        
      end
    end
    
    >> B.foo
    => In foo
    >> B.new.bar
    => In bar
    => In foo