22

How would you list out the modules that have been included in a specific class in a class hierarchy in Ruby? Something like this:

module SomeModule
end

class ParentModel < Object
  include SomeModule
end

class ChildModel < ParentModel
end

p ChildModel.included_modules #=> [SomeModule]
p ChildModel.included_modules(false) #=> []

Listing the ancestors makes the module appear higher in the tree:

p ChildModel.ancestors #=> [ChildModel, ParentModel, SomeModule, Object, Kernel]
Lance
  • 75,200
  • 93
  • 289
  • 503

1 Answers1

19

As far as I understand your question, something like this is what you are looking for:

class Class
  def mixin_ancestors(include_ancestors=true)
    ancestors.take_while {|a| include_ancestors || a != superclass }.
    select {|ancestor| ancestor.instance_of?(Module) }
  end
end

However, I don't fully understand your testcases: why is SomeModule listed as an included module of ChildModel even though it isn't actually included in ChildModel but in ParentModel? And conversely, why is Kernel not listed as an included module, even though it is just as much in the ancestors chain as SomeModule? And what does the boolean argument to the method mean?

(Note that boolean arguments are always bad design: a method should do exactly one thing. If it takes a boolean argument, it does by definition two things, one if the argument is true, another is the argument is false. Or, if it does only one thing, then this can only mean that it ignores its argument, in which case it shouldn't take it to begin with.)

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • I'm not the original poster, but I think I can answer your question re: the boolean argument. Lance is expecting this `.included_modules` method to behave like `#methods`, `#public_methods` and other similar methods do in Ruby. On those, a `true` value means "show me the methods that this object got from its class IN ADDITION TO those it got from its ancestor classes and included modules". A false value does not return these additional methods. – pablobm Jun 27 '13 at 11:41