Private module methods in Ruby

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

    You can use the "included" method to do fancy things when a module is mixed in. This does about what you want I think:

    module Foo
      def self.included(base)
        class << base 
          def public_method
            puts "public method"
          end
          def call_private
            private_method
          end
          private
          def private_method
            puts "private"
          end
        end
      end
    end
    
    class Bar
      include Foo
    end
    
    Bar.public_method
    
    begin
      Bar.private_method
    rescue
      puts "couldn't call private method"
    end
    
    Bar.call_private
    

提交回复
热议问题