22

When you include modules in a class or other module you can call

@mymod.included_modules

to get a list of modules included.

Is there an equivalent for listing the modules a module was extended by?

module Feature1
end

module Feature2
  extend Feature1
end

Feature2.extended_modules #=> [Feature1]
1
  • the ancestors function might be of some help Commented Mar 4, 2011 at 17:35

3 Answers 3

37
Feature2.singleton_class.included_modules # => [Feature1, ...]
1
  • 3
    This should be the selected answer.
    – Aeramor
    Commented Jun 18, 2016 at 4:39
19

They're there, you just have to look in the right place:

(class << Feature2; self end).included_modules   # [Feature1, Kernel]

We can generalize like this:

class Module
  # Return any modules we +extend+
  def extended_modules
    (class << self; self end).included_modules
  end
end

# Now get those extended modules peculiar to Feature2
Feature2.extended_modules - Module.extended_modules # [Feature1]
3
  • 1
    Ah, yes. I remember this now. There's some German name associated with what this is.
    – Mario
    Commented Mar 4, 2011 at 17:49
  • 11
    I think the community has settled on singleton class. There's even an Object#singleton_class method in Ruby 1.9 which returns an object's singleton class. The reason why this works is of course that extend is literally just singleton_class.include. Commented Mar 5, 2011 at 0:36
  • I just tried your answer in irb and its awesome :) but its singleton_class.included_modules Commented Sep 21, 2013 at 0:28
1

All Ruby modules can be listed from CLI (Command Line), itself as follows:

ruby -e 'puts Gem::Specification.all().map{|g| [g.name, g.version.to_s] }'

OR

ruby -rubygems -e 'puts Gem::Specification.all().map{|g| [g.name, g.version.to_s] }'

Hope this helps to some extent!!!

Not the answer you're looking for? Browse other questions tagged or ask your own question.