Created
February 22, 2014 01:33
-
-
Save jeremywrowe/9147263 to your computer and use it in GitHub Desktop.
I see the top implementation of class level private methods a lot. Please understand that the private means nothing in that case. Do you know why? :)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The wrong way to make a class level method private | |
class Foo | |
def self.bar | |
p "bar" | |
end | |
private | |
def self.baz | |
p "baz" | |
end | |
end | |
Foo.bar # => "bar" | |
Foo.baz # => "baz" | |
# The right way to make a class level method private | |
class Cat | |
class << self | |
def hat | |
p "hat" | |
end | |
private | |
def hidden | |
end | |
end | |
end | |
Cat.hat # => "hat" | |
Cat.hidden # => private method `hidden' called for Cat:Class (NoMethodError) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For making class methods
private
, you can also useprivate_class_method
.As for why the
private
keyword does nothing forself.foo
style method declarations, I've come to understand it this way (after some late night reading!):You cannot make methods
private
when they are given an explicit receiver (as inself.baz
). Therefore, to make class methods private, you have to open up the "eigenclass" of the class. In that context, the class (Cat
orFoo
is the implicit receiver (it's an instance of the eigenclass), and so doingMakes the
Cat
class itself (and not an instance of theCat
class) the implicit receiver. Now you can declare private class methods.Maybe none of that matters anyway because I can just do
Cat.send(:hidden)
and break the visibility rules!