Ruby: Is it possible to define a class method in a module?

前端 未结 5 1029
萌比男神i
萌比男神i 2020-12-24 00:19

Say there are three classes: A, B & C. I want each class to have a class method, say self.foo, that has exactly the s

5条回答
  •  Happy的楠姐
    2020-12-24 00:50

    Yep

    module Foo
      def self.included(base)
        base.extend(ClassMethods)
      end
      module ClassMethods
        def some_method
          # stuff
        end
      end
    end
    

    One possible note I should add - if the module is going to be ALL class methods - better off just using extend ModuleName in the Model and defining the methods directly in the module instead - rather than having a ClassMethods module inside the Module, a la

     module ModuleName
       def foo
         # stuff
       end
     end
    

提交回复
热议问题