Can I invoke an instance method on a Ruby module without including it?

前端 未结 10 1343
情歌与酒
情歌与酒 2020-12-07 07:37

Background:

I have a module which declares a number of instance methods

module UsefulThings
  def get_file; ...
  def delete_file; ...

  def forma         


        
10条回答
  •  长情又很酷
    2020-12-07 07:50

    If a method on a module is turned into a module function you can simply call it off of Mods as if it had been declared as

    module Mods
      def self.foo
         puts "Mods.foo(self)"
      end
    end
    

    The module_function approach below will avoid breaking any classes which include all of Mods.

    module Mods
      def foo
        puts "Mods.foo"
      end
    end
    
    class Includer
      include Mods
    end
    
    Includer.new.foo
    
    Mods.module_eval do
      module_function(:foo)
      public :foo
    end
    
    Includer.new.foo # this would break without public :foo above
    
    class Thing
      def bar
        Mods.foo
      end
    end
    
    Thing.new.bar  
    

    However, I'm curious why a set of unrelated functions are all contained within the same module in the first place?

    Edited to show that includes still work if public :foo is called after module_function :foo

提交回复
热议问题