Ruby:是否可以在模块中定义类方法?
假设有三类: A , B和C 我希望每个类有一个类方法,说self.foo ,具有完全相同的代码为A , B & C 。 
 是否可以在一个模块中定义self.foo并将这个模块包含在A , B和C ? 我试图这样做,并得到一个错误消息,说foo不被识别。 
 module Common def foo puts 'foo' end end class A extend Common end class B extend Common end class C extend Common end A.foo 
或者,您可以在之后扩展课程:
 class A end class B end class C end [A, B, C].each do |klass| klass.extend Common end 
是的
 module Foo def self.included(base) base.extend(ClassMethods) end module ClassMethods def some_method # stuff end end end 
 我应该添加一个可能的注意事项 – 如果模块将是所有类方法 – 最好在模型中使用extend ModuleName ,而不是直接在模块中定义方法 – 而不是在模块内部具有ClassMethods模块, 
  module ModuleName def foo # stuff end end 
  Rails 3引入了一个名为ActiveSupport::Concern的模块,其目的是简化模块的语法。 
 module Foo extend ActiveSupport::Concern module ClassMethods def some_method # stuff end end end 
它允许我们在模块中保存几行“样板”代码。
 这是基本的ruby混合function,使ruby如此特别。 当extend将模块方法转换为类方法时, include / extends类或模块中include将模块方法转换为实例方法。 
 module SomeClassMethod def a_class_method 'I´ma class method' end end module SomeInstanceMethod def an_instance_method 'I´m an instance method!' end end class SomeClass include SomeInstanceMethods extend SomeClassMethods end instance = SomeClass.new instance.an_instance_method => 'I´m an instance method!' SomeClass.a_class_method => 'I´ma class method'