Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block inheritance of static function in Ruby

A small test case :

class A
  def self.print
    puts "Hello A"
  end
end


class B < A
end

A.print
B.print

This outputs :

Hello A
Hello A

I would like to block the inheritance of the print function defined in class A. Is it possible?

Output wanted :

Hello A
`<main>': undefined method `print' for B:Class (NoMethodError)

I found private_class_method but it's not exaclty what I'm looking for as it fails on A.print call.

like image 568
Pol0nium Avatar asked Aug 04 '26 18:08

Pol0nium


1 Answers

class A
  def self.print
    puts "Hello A"
  end

  def self.inherited(klass)
    class << klass
      undef :print
    end
  end
end

class B < A
end

A.print
# Hello A

B.print
# private method `print' called for B:Class (NoMethodError)
like image 195
Patrick Oscity Avatar answered Aug 07 '26 17:08

Patrick Oscity