Reputation: 238667
I'm trying to get the name of the parent module of my subclass:
module Special
class BaseController
def self.action
puts Module.nesting.inspect # i want this to be relative to self
end
end
end
module Foobar
class Controller < Special::BaseController
action do
# should print Foobar::Controller
end
end
end
How can I get the parent module of the subclass instead of the base class?
Upvotes: 1
Views: 2033
Reputation: 238667
This ended up being easier than I thought. Calling self.to_s
will give you the full name (including modules). So you can grab the second to last one:
class_name = self.to_s.split('::')[-2]
Upvotes: 1
Reputation: 160551
I think the problem is that Ruby hasn't finished defining the module and class at the point you want to know about it. Once you've closed the definitions you could create an instance of it and find out:
irb(main):017:0> Foobar::Controller.new.class
Foobar::Controller < Special::BaseController
Then it's a case of doing a string split:
irb(main):033:0> Foobar::Controller.new.class.to_s.split('::')
[
[0] "Foobar",
[1] "Controller"
]
Upvotes: 0