Define a class method in a module

后端 未结 2 764
我寻月下人不归
我寻月下人不归 2021-01-26 19:17

I mean, I want to create a class method in my module that will be used by the class who includes the module. They are in separated files.

By far I have something like th

相关标签:
2条回答
  • 2021-01-26 20:10

    Following Ricardo's answer, consider an idiom common among Ruby programmers - enclose your module's class methods into inner module, called ClassMethods(that's a mouthful, I know), and use and Module#included hook to extend base class with ClassMethods module.

    More information here: http://www.railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/

    0 讨论(0)
  • 2021-01-26 20:17

    You can extend the module in your class, your code should be like this:

    module Base
      def all
        puts "All Users"
      end
    end
    
    class User
      extend Base
    end
    

    When you do something like this:

    module MyModule
      def self.module_method
        puts "module!"
      end
    end
    

    You're actually adding the method in the module itself, you could call the previous method like this:

    MyModule.module_method
    

    There is a way to just include the module and get the behaviour that you want, but I don't think this could be considered the "way to go". Look at the example:

    module Base
      def self.included(klass)
        def klass.all
          puts "all users"
        end
      end
    end
    
    class User
      include Base
    end
    

    But like I said, if you can go with the extend class method, it is a better suit.

    0 讨论(0)
提交回复
热议问题