When are modules included in a Ruby class running in rails?
Asked Answered
L

1

2

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?

Lophophore answered 20/8, 2010 at 0:51 Comment(1)
i would think it would get loaded when the model containing the module is called.Dunham
V
4

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.

Vesture answered 20/8, 2010 at 6:12 Comment(2)
unfortunately "Rails autoloads modules/classes when you first use them" means I probably can't get what I want to do working, but that doesn't make the answer any less correct. Thanks.Lophophore
shouldn't it be @@rateable_object instead of @rateable_objects ?Unemployed

© 2022 - 2024 — McMap. All rights reserved.