Created
December 18, 2014 09:12
-
-
Save Integralist/bb8760d11a03c88da151 to your computer and use it in GitHub Desktop.
Ruby: private class level methods
This file contains hidden or 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
| class Foo | |
| class << self | |
| def bar | |
| p "im public" | |
| end | |
| private | |
| def baz | |
| p "im private" | |
| end | |
| end | |
| end | |
| Foo.bar # => im public | |
| Foo.baz # => NoMethodError: private method `baz' called for Foo:Class |
This file contains hidden or 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
| class Foo | |
| def self.bar | |
| p "im public" | |
| end | |
| private | |
| def self.baz | |
| p "im private" | |
| end | |
| end | |
| Foo.bar # => im public | |
| Foo.baz # => im private |
Author
Author
You can get the second example (def self.baz) to work by using private_class_method :baz...
class Foo
def self.bar
p "im public"
end
def self.baz
p "im private"
end
private_class_method :baz
end
Foo.bar # => im public
Foo.baz # => NoMethodError: private method `baz' called for Foo:ClassSee also https://stackoverflow.com/a/12925407/322020 and other answers there.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It has been suggested that
privateis actually a method (not a directive or special syntax) and so theprivatemethod only changes the visibility of instance methods. Class methods on the other hand are instance methods of the Eigenclass.In the first example (
class << self) theprivatemethod goes through the Eigenclass (so the class methods technically become instance methods on the Eigenclass and so theprivatedirective is enforced) but in the second example theprivatemethod goes through theFooclass (and its class level methods aren't affected by theprivatemethod).