Skip to content

Instantly share code, notes, and snippets.

@jeremywrowe
Created February 22, 2014 01:33
Show Gist options
  • Save jeremywrowe/9147263 to your computer and use it in GitHub Desktop.
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? :)
# 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)
@speric
Copy link

speric commented Feb 22, 2014

For making class methods private, you can also use private_class_method.

As for why the private keyword does nothing for self.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 in self.baz). Therefore, to make class methods private, you have to open up the "eigenclass" of the class. In that context, the class (Cat or Foo is the implicit receiver (it's an instance of the eigenclass), and so doing

class Cat
  class << self
    ...
  end
end

Makes the Cat class itself (and not an instance of the Cat 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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment