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

前端 未结 10 1326
情歌与酒
情歌与酒 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 08:00

    A. In case you, always want to call them in a "qualified", standalone way (UsefulThings.get_file), then just make them static as others pointed out,

    module UsefulThings
      def self.get_file; ...
      def self.delete_file; ...
    
      def self.format_text(x); ...
    
      # Or.. make all of the "static"
      class << self
         def write_file; ...
         def commit_file; ...
      end
    
    end
    

    B. If you still want to keep the mixin approach in same cases, as well the one-off standalone invocation, you can have a one-liner module that extends itself with the mixin:

    module UsefulThingsMixin
      def get_file; ...
      def delete_file; ...
    
      def format_text(x); ...
    end
    
    module UsefulThings
      extend UsefulThingsMixin
    end
    

    So both works then:

      UsefulThings.get_file()       # one off
    
       class MyUser
          include UsefulThingsMixin  
          def f
             format_text             # all useful things available directly
          end
       end 
    

    IMHO it's cleaner than module_function for every single method - in case want all of them.

提交回复
热议问题