Search code examples
rubyprotected

How to make a protected singleton method


How can I make the following method some_protected protected or private? It should be implemented without inheritance.

module Sample
  def self.some_public
    some_protected
  end

  protected

  def self.some_protected
    puts 'Bingo!'
  end
end

Sample::some_public     # Bingo!
Sample::some_protected  # Bingo! (but expected an error that method is not accessible)

Solution

  • Working within the singleton class is probably the easiest.

    module Sample; end
    
    class <<Sample
      def some_public
        some_protected
      end
      protected def some_protected
        puts 'Bingo!'
      end
    end