lib文件夹中的模块类

时间:2014-04-20 23:30:59

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

我有一个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

2 个答案:

答案 0 :(得分:0)

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

然后在ActiveRecord模型中,如Post

class Post < AR
  include Ready
end

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

module Ready

  extend ActiveSupport::Concern

  included do
    has_many :likes
  end
end

希望有所帮助,

问候

答案 1 :(得分:0)

来自extend的文档:

  

从obj中添加每个模块的实例方法作为a   参数。

因此,您无法通过扩展类访问此类。请查看包含模块而不是扩展模块(也请阅读ActionSupport::Concern模块)或使用self.extended方法(参考here