Private module methods in Ruby

后端 未结 9 1116
深忆病人
深忆病人 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:07

    Make a private module or class

    Constants are never private. However, it's possible to create a module or class without assigning it to a constant.

    So an alternative to :private_class_method is to create a private module or class and define public methods on it.

    module PublicModule
      def self.do_stuff(input)
        @private_implementation.do_stuff(input)
      end
    
      @private_implementation = Module.new do
        def self.do_stuff(input)
          input.upcase # or call other methods on module
        end
      end
    end
    

    Usage:

    PublicModule.do_stuff("whatever") # => "WHATEVER"
    

    See the docs for Module.new and Class.new.

提交回复
热议问题