How to get the module that a class resides in?

J

jc

How can I do the equivalent of the following?

class Foo
class Bar; end
end
Foo::Bar.module # => Foo
 
R

Ryan Davis

How can I do the equivalent of the following?

class Foo
class Bar; end
end
Foo::Bar.module # => Foo

class Class
def path
result = []
self.name.split(/::/).inject(Object) do |c, n|
result << c.const_get(n)
result.last
end
return result
end
end

class Foo
class Bar
end
end

p Foo::Bar.path
# => [Foo, Foo::Bar]

I have a hard time understanding why I needed to write that.
Module.nesting looks close, but doesn't quite cut it (and is a pain
since you have to call it within a module scope).
 
J

jc

What I'm really looking for is a more generic method, something like
Object#parent_namespace:

class A; end
module B
class C
D = A.new
end
end

puts A.parent_namespace => Object
puts B.parent_namespace => Object
puts B::C.parent_namespace => B
puts B::C::D.parent_namespace => C
puts B::C::D.class.parent_namespace => Object

So that lookups could be easily done:

obj.parent_namespace.const_get:)name)
obj.parent_namespace.send(name, value)

Is there perhaps a way to do this via the Ruby C API?
 
C

Csaba Henk

What I'm really looking for is a more generic method, something like
Object#parent_namespace:

class A; end
module B
class C
D = A.new
end
end

puts A.parent_namespace => Object
puts B.parent_namespace => Object
puts B::C.parent_namespace => B
puts B::C::D.parent_namespace => C
puts B::C::D.class.parent_namespace => Object

So that lookups could be easily done:

obj.parent_namespace.const_get:)name)
obj.parent_namespace.send(name, value)

Is there perhaps a way to do this via the Ruby C API?

Although far from being elegant, and won't work for anonymous classes,
you can get these methods by parsing what "inspect" and "name" gives
you.

Csaba
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top