Below is the code making me confused :
class Foo
protected
def self.baz;end
end
Foo.protected_methods() # => [] # I expected [:baz]
Foo.public_methods(false) # => [:baz, :allocate, :new, :superclass]
Why am I getting empty?
Below is the code making me confused :
class Foo
protected
def self.baz;end
end
Foo.protected_methods() # => [] # I expected [:baz]
Foo.public_methods(false) # => [:baz, :allocate, :new, :superclass]
Why am I getting empty?
Excerpts from Arup R.'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
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 C. wrote in post #1132886:
Excerpts from Arup R.'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.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs