Private module methods in Ruby

后端 未结 9 1108
深忆病人
深忆病人 2020-12-04 06:21

I have a two part question

Best-Practice

  • I have an algorithm that performs some operation on a data structure using the public interfa
9条回答
  •  鱼传尺愫
    2020-12-04 07:09

    There's also Module.private_class_method, which arguably expresses more intent.

    module Foo
      def self.included(base)
        base.instance_eval do
          def method_name
            # ...
          end
          private_class_method :method_name
        end
      end
    end
    

    For the code in the question:

    module Thing
      def self.pub; puts "Public method"; end
      def self.priv; puts "Private method"; end
      private_class_method :priv
    end
    

    Ruby 2.1 or newer:

    module Thing
      def self.pub; puts "Public method"; end
      private_class_method def self.priv; puts "Private method"; end
    end
    

提交回复
热议问题