Confusion with protected methods

Below is the code making me confused :

class Foo
  protected
  def self.baz;end
end

Foo.protected_methods() # => []

Why am I getting empty? I expected [:baz]

···

--
Posted via http://www.ruby-forum.com/.

Excerpts from Arup Rakshit's message of 2014-01-12 10:32:16 +0100:

Below is the code making me confused :

class Foo
  protected
  def self.baz;end
end

Foo.protected_methods() # => []

Why am I getting empty? I expected [:baz]

Your problem is that the Module#protected method you use ony applies to instance
methods you define, not to class method. This means that the baz class method
you define is not protected at all. Look:

class Foo
  protected
  def self.baz
    puts "Foo.baz"
  end
end

Foo.baz
#output: Foo.baz

If you defined an instance method, it would have worked as you expected:

class Foo
  protected
  def baz #note that now this is an instance method
    puts "Foo#baz"
  end
end

Foo.new.baz
=> NoMethodError: protected method `baz' called for #<Foo:0x00000000c65458>

To make a class method protected, you have to do so from the class's singleton
class:

class Foo
  def self.baz
    puts "Foo.baz"
  end
end

class << Foo
  protected :baz
end

Foo.baz
=> NoMethodError: protected method `baz' called for Foo:Class

I hope this helps

Stefano

Stefano Crocco wrote in post #1132886:

Excerpts from Arup Rakshit's message of 2014-01-12 10:32:16 +0100:

Your problem is that the Module#protected method you use ony applies to
instance
methods you define, not to class method. This means that the baz class
method

Thanks for your explanation.

···

--
Posted via http://www.ruby-forum.com/.