Ruby Basics : Hiding a Class Method

Objective


To learn how the private keyword differs when it is used to hide class methods.

Steps


Step 1

class Foo
  def self.greet
    p 'hi'
  end  
end

Foo.greet

This prints 'hi'.

Step 2

class Foo
  def self.greet
    p 'hi'
  end

  private

  def bar
    p 'bar'
  end

end

Foo.new.bar

We get:

NoMethodError: private method ‘bar’ called for #<Foo:0x00200>. 

This is as expected.

Step 3

class Foo
  def self.greet
    p 'hi'
  end

  private

  def self.gold
    p 'gold'
  end
end

Foo.gold

This is a surprise because it prints gold. The private keyword does not prevent the gold from getting called outside of Foo class.

Step 4

How do we hide a class method?

class Foo

  class << Foo
    private 

    def gold
      p 'gold'
    end
  end
end

Foo.gold

Now we get:

NoMethodError: private method ‘gold’ called for Foo:Class

Step 5

class Foo
  def self.greet
    gold
  end

  private

  class << Foo
    private 

    def gold
      p 'gold'
    end
  end
end

Foo.greet

This prints 'gold'. So, you can use the public interface that calls the private class method. It will work.

Step 6

You can also use privateclassmethod to make existing class methods private as suggested by Matt Brictson on rubyflow.com.

class Foo

  private_class_method :gold

  def self.gold
    p 'gold'
  end
end

Foo.gold

If you run this, you will see:

NameError: undefined method ‘gold’ for class `Class'

Summary


In this article, we saw how the private keyword does not hide class methods and what we can do if we need to hide them.


Related Articles


Create your own user feedback survey