Friday, March 25, 2011

How to make a class method private

If you want to make a class method private, you must put the private keyword inside the class << self section:

This works:
class Test
  class << self
    private

    def foo
      puts "bar"
    end
  end

  foo         #=> "bar"
end

Test.foo      #=> NoMethodError: 'foo' is a private method;
              #   That's we want!

This works, too:
class Test
  class << self
    def foo
      puts "bar"
    end

    private :foo
  end

  foo         #=> "bar"
end

Test.foo      #=> NoMethodError

And this:
class Test
  def self.foo
    puts "bar"
  end

  class << self
    private :foo
  end

  foo         #=> "bar"
end

Test.foo      #=> NoMethodError

Putting the private outside class << self doesn't work:
class Test
  def self.foo
    puts "bar"
  end

  private self.:foo     #=> Syntax error: unexpected tSYMBEG
  private :self.foo     #=> Error: undefined method "foo" for :self
  private :"self.foo"   #=> Error: undefined method "self.foo" for Test
end

And the following tests won't work, too:
class Test
  class << self
    private
  end      # by closing this block, the scope of "private" is also closed,
           # even if we reopen the block right next:

  class << self
    def foo
      puts "bar"
    end
  end

  foo         #=> "bar"
end

Test.foo      #=> "bar"

class Test
  class << self
    private
  end

  def self.foo
    puts "bar"
  end

  foo         #=> "bar"
end

Test.foo      #=> "bar"

No comments:

Post a Comment