开发者

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

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 i开发者_运维问答nformation this way early in the process, is there anyway to accomplish this?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜