lib文件夹中的模块类

我有一个lib文件lister_extension.rb

module ListerExtension def lister puts "#{self.class}" end end 

并发布模型

 class Post < ActiveRecord::Base has_many :reviews extend ListerExtension def self.puts_hello puts "hello123123" end end 

当我在rails c调用它时一切都很好:

 2.1.1 :003 > Post.lister Class => nil 

但是当我想在我的模块中添加一个类时会发生什么?

例如:

 module ListerExtension class ready def lister puts "#{self.class}" end end end 

我收到这个错误

 TypeError: wrong argument type Class (expected Module) 

当我在rails c中调用Post.first

extend文档:

添加obj作为参数给出的每个模块的实例方法。

因此,您无法通过扩展类访问此类。 看一下包含模块而不是扩展它们(也可以阅读ActionSupport::Concern模块)或者使用self.extended方法( self.extended 这里 )

TL; DR,在ruby中你不能用类扩展,你扩展/包含模块

问候

更新:关注的示例包括/扩展与activesupport关注

 module Ready extend ActiveSupport::Concern # this is an instance method def lister .... end #this are class methods module ClassMethods def method_one(params) .... end def method_two .... end end end 

然后在像Active这样的ActiveRecord模型中

 class Post < AR include Ready end 

使用此过程,您将免费获取实例方法和类方法,也可以设置一些宏,如使用包含的块,

 module Ready extend ActiveSupport::Concern included do has_many :likes end end 

希望有所帮助,

问候