问题描述
module Test
def self.model_method
puts "this is a module method"
end
end
class A
include Test
end
A.model_method
这将是错误的:
未定义的方法`model_method' for A:Class (NoMethodError)
但是当我使用 A 的元类时,它可以工作:
But when I use metaclass of A. it works:
module Test
def model_method
puts "this is a module method"
end
end
class A
class << self
include Test
end
end
A.model_method
有人能解释一下吗?
推荐答案
如果你想在包含一个模块时将类方法和实例方法混合到一个类中,你可以遵循以下模式:
If you want to have both class methods and instance methods mixed into a class when including a module, you may follow the pattern:
module YourModule
module ClassMethods
def a_class_method
puts "I'm a class method"
end
end
def an_instance_method
puts "I'm an instance method"
end
def self.included(base)
base.extend ClassMethods
end
end
class Whatever
include YourModule
end
Whatever.a_class_method
# => I'm a class method
Whatever.new.an_instance_method
# => I'm an instance method
基本上是为了过度简化它,你extend
来添加类方法,你include
来添加实例方法.当一个模块被包含时,它的 #included
方法被调用,使用它被包含的实际类.从这里你可以使用另一个模块的一些类方法extend
.这是一种很常见的模式.
Basically to over-simplify it, you extend
to add class methods and you include
to add instance methods. When a module is included, it's #included
method is invoked, with the actual class it was included in. From here you can extend
the class with some class methods from another module. This is quite a common pattern.
另见:http://api.rubyonrails.org/classes/ActiveSupport/Concern.html
这篇关于为什么模块的“self"方法不能成为类的单例方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!