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.
精彩评论