When are modules included in a Ruby class running in rails?

▼魔方 西西 提交于 2019-12-13 12:32:11

问题


I'm trying to write a method that tells me every class that includes a particular Module. It looks like this -

def Rating.rateable_objects
  rateable_objects = []
  ObjectSpace.each_object(Class) do |c|
    next unless c.include? Rateable
    rateable_objects << c
  end
  rateable_objects
end

Where "Rateable" is my module that I'm including in several models.

What i'm finding is that this method return [] if i call it immediately after booting rails console or running the server. But if i first instantiate an instance of one of the consuming models it will return that model in the result.

So when do modules get included? I'm guessing later in the process than when he app starts up. If i can't get this information this way early in the process, is there anyway to accomplish this?


回答1:


They are included when the include statement is executed when the class is defined. Rails autoloads modules/classes when you first use them. Also, you might try something like this:

module Rateable
  @rateable_object = []
  def self.included(klass)
    @rateable_objects << klass
  end
  def rateable_objects
    @rateable_objects
  end
end

This will build the list as classes include the module.



来源:https://stackoverflow.com/questions/3527445/when-are-modules-included-in-a-ruby-class-running-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!