How to create a private class method?

后端 未结 8 1325
北荒
北荒 2020-12-02 04:43

How come this approach of creating a private class method works:

class Person

  def self.get_name
    persons_name
  end

  class << self

    private         


        
8条回答
  •  孤城傲影
    2020-12-02 04:52

    ExiRe wrote:

    Such behavior of ruby is really frustrating. I mean if you move to private section self.method then it is NOT private. But if you move it to class << self then it suddenly works. It is just disgusting.

    Confusing it probably is, frustrating it may well be, but disgusting it is definitely not.

    It makes perfect sense once you understand Ruby's object model and the corresponding method lookup flow, especially when taking into consideration that private is NOT an access/visibility modifier, but actually a method call (with the class as its recipient) as discussed here... there's no such thing as "a private section" in Ruby.

    To define private instance methods, you call private on the instance's class to set the default visibility for subsequently defined methods to private... and hence it makes perfect sense to define private class methods by calling private on the class's class, ie. its metaclass.

    Other mainstream, self-proclaimed OO languages may give you a less confusing syntax, but you definitely trade that off against a confusing and less consistent (inconsistent?) object model without the power of Ruby's metaprogramming facilities.

提交回复
热议问题