As we know, the private methods cannot be called with an explicit receiver in ruby. But when I define a class, I can invoke a private class method by the class itself.
For example:
class A
private
def self.test
puts "hello,world!"
end
end
A.test => hello,world!
A.new.test NoMethodError: private method `test' called for #<A:0x007f80b91a10f8>
it is contradictory with the definition of private. Anyone can tell me the reason. Thanks in advance!
private
only affects instance methods. To make a private class method, useprivate_class_method
:or
EDIT: Yet another way to do it is to define methods on the metaclass - they will behave as class methods.
Unfortunately, there is no such thing as
protected_class_method
- but this last option gives us a hint on how to do it:but note that it can be only called from class methods of the descendant classes: