Ruby A. schrieb:
Is there a way to get only the modules included by a given class.
Using included_modules returns also the modules that are included by
the superclass(es).
(…)
As a given module may be included several times in the class
hierarchy (e.g. by the class and by one of its superclass), just
getting all included modules and removing the included modules from
the superclasses may not be a solution. The given module may have
been removed erroneously.
Including a module in a class that already has been included by one of
its superclasses doesn’t change the inheritance hierarchy:
module M
end
class P
include M
end
class C < P
end
p C.ancestors # => [C, P, M, Object, Kernel]
class C
include M
end
p C.ancestors # => [C, P, M, Object, Kernel]
The only way to create the situation you describe above would be to
include the module in the child class before including it in the
superclass. If you want to detect this, you could try the following
code:
class Class
def my_own_included_modules
ancestors.inject([]) { |acc, mod|
break acc if mod == superclass
acc << mod unless mod == self
acc
}
end
end
p P.my_own_included_modules # => [M]
p C.my_own_included_modules # => []
class P2
end
class C2 < P2
include M
end
class P2
include M
end
p C2.ancestors # => [C2, M, P2, M, Object, Kernel]
p P2.my_own_included_modules # => [M]
p C2.my_own_included_modules # => [M]
Out of curiosity: why do you need this?
Regards,
Pit