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

前端 未结 5 1036
萌比男神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条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-24 01:04

    Just wanted to extend Oliver's answer Define Class methods and instance methods together in a module.

    module Foo
     def self.included(base)
       base.extend(ClassMethods)
     end
     module ClassMethods
       def a_class_method
         puts "ClassMethod Inside Module"
       end
     end
    
     def not_a_class_method
       puts "Instance method of foo module"
     end
    end
    
    class FooBar
     include Foo
    end
    
    FooBar.a_class_method
    
    FooBar.methods.include?(:a_class_method)
    
    FooBar.methods.include?(:not_a_class_method)
    
    fb = FooBar.new
    
    fb.not_a_class_method
    
    fb.methods.include?(:not_a_class_method)
    
    fb.methods.include?(:a_class_method)
    

提交回复
热议问题