Access class from internal module

I want to be able to do this:

class IncludingClass
  include IncludedModule
end

module IncludedModule
  self.parent_class # => IncludingClass, I wish
end

Any ideas? Sorry for the brevity. Typing it on the phone. In any case, I looked around and could not find it, which seems surprising for such a encountered aprogrammable language.

0
source share
1 answer

I do not think the modules track what included them. But they work MyModule.included(SomeClass)like a callback when they turn on, so you can track yourself.

module IncludedModule

  # Array to store included classes
  @@included_classes = []

  # Called when this module is included.
  # The including class is passed as an argument.
  def self.included(base)
    @@included_classes << base
  end

  # Getter for class variable
  def self.included_classes
    @@included_classes
  end
end

# Include the module
class IncludingClass
  include IncludedModule
end

# Ask the module what included it.
puts IncludedModule.included_classes #=> [IncludingClass]

There is probably a way to scan all the declared classes and ask them what they turned on through SomeClass.included_modules, but this kind of hairy, and will be much slower.

+1
source

All Articles