假设情况如下:
module Extension
def self.included(recipient)
recipient.extend(ModelClassMethods)
end
module ModelClassMethods
def self.msg
puts 'Hi from module'
end
end
end
class B
include Extension
end
为什么 B.msg 不可用?
>> B.msg
NoMethodError: undefined method `msg' for B:Class
from (irb):16
我是不是想错了?这似乎并不难完成。
最佳答案
ModelClassMethods
模块中的 msg
方法应该声明为实例方法而不是类方法,因为扩展接收类的行为已经使它成为类方法.所以:
module Extension
def self.included(recipient)
recipient.extend(ModelClassMethods)
end
module ModelClassMethods
def msg # Note lack of 'self.'
puts 'Hi from module'
end
end
end
关于ruby-on-rails - 如何将类级方法扩展到 Rails 中的单独模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2232535/