Question

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?

Was it helpful?

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

OTHER TIPS

... 2.67 years later ...

A simpler way to solve this is with class_eval

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

class B < A
  def bar
    self.class.class_eval { foo }
  end
end

B.new.bar    # prints "In foo"

So far, the only solution I've found is to define a class method in the subclass that calls the class method in the superclass. Then I can call this method in the subclass' instance method.

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

class B < A
  def self.call_foo
    puts "In call_foo"
    A::foo
  end

  def bar
    puts "In bar"
    self.class.call_foo
  end
end

Is this really necessary?

I'd probably just make A.foo public. Otherwise send will do it, since it bypasses access controls:

A.send(:foo)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top