Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you list included Modules in a Ruby Class?

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]
like image 379
Lance Avatar asked Aug 15 '10 17:08

Lance


People also ask

Can we define module inside class Ruby?

You can define and access instance variables within a module's instance methods, but you can't actually instantiate a module. A module's instance variables exist only within objects of a class that includes the module.

How do you reference a module in Ruby?

As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.

What is the difference between extend and include in Ruby?

In simple words, the difference between include and extend is that 'include' is for adding methods only to an instance of a class and 'extend' is for adding methods to the class but not to its instance.

Can modules include other modules Ruby?

Indeed, a module can be included in another module or class by using the include , prepend and extend keywords. Before to start this section, feel free to read my article about the Ruby Object Model if you're unfamiliar with the ancestor chain in Ruby.


1 Answers

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.)

like image 82
Jörg W Mittag Avatar answered Oct 08 '22 05:10

Jörg W Mittag