Where to place private methods in Ruby?

前端 未结 10 1034
故里飘歌
故里飘歌 2021-01-30 00:50

Most of the blogs or tutorials or books have private methods at the bottom of any class/module. Is this the best practice?

I find having private methods as and when nece

10条回答
  •  庸人自扰
    2021-01-30 01:24

    One style is to group methods together so that you only use private and protected once per class at most. Another style is to specify visibility right after the method definition:

    class Example
      def my_private_method
      end
      private :my_private_method
    
      def my_public_method
      end
    end
    

    As of Ruby 2.1.0 def returns the method name as a symbol, so a more streamlined style is possible:

    class Example
      private def my_private_method
      end
    
      def my_public_method
      end
    
      protected def my_protected_method
      end
    
      private_class_method def self.my_private_class_method
      end
    end
    

    (Note that we use private_class_method for class methods -- otherwise we'd get NameError: undefined method since private expects an instance method. Even when using it as a macro like in the original example it only affects the visibility of instance methods.)

    I like this inline visibility style best, as it allows you to organize methods as you wish. It decreases the risk of adding a new method in the wrong place and inadvertently making it private.

    As for the class method syntax, you can handle it this way instead:

    class Example
      private def my_private_method
      end
    
      class << self
        private def my_private_class_method
        end
      end
    end
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题