Module M
Class C
end
end
What I need is something like:
M.was_defined_here?(M::C)
M.classes.include?(M::C)
Does this exists somehow?
I know I could parse M::C.name. But someebody could have the idea to change Module#name, to make it more astetic or something. I want a clean solution.
M.constants.map {|c| M.const_get(c)}.include?(M::C)
Or, from johannes' comment, using find (will perform better if the class does exist in M and doesn't happen to be the last constant in M - though it should rarely make a measurable difference):
M.constants.find {|c| M.const_get(c) == M::C }
Edit: Since you actually just want a boolean result, this any?
makes more send than find
:
M.constants.any? {|c| M.const_get(c) == M::C }
sepp2k's answer won't work if M::C
is not defined at all, since Ruby will raise a NameError
in that block.
Try this:
M.constants.include?('C')
If you're worried that you have a reference to M::C
by a different name, like so:
module M
class C
end
end
MY_M_C = M::C
then you can test whether MY_M_C
is the same as M
's C
like so:
M.constants.include?('C') ? MY_M_C == M.const_get(:C) : false