Skip to content

Instantly share code, notes, and snippets.

@deepak
Created December 10, 2013 05:41
Show Gist options
  • Select an option

  • Save deepak/7886193 to your computer and use it in GitHub Desktop.

Select an option

Save deepak/7886193 to your computer and use it in GitHub Desktop.
find the parent module of a class
# find the parent module of a class
# https://twitter.com/postmodern_mod3/status/410270060721082368
# using http://ruby-doc.org/core-2.0.0/Module.html#method-c-nesting
# or else by parsing the string representation of the class name
module Foo
module Bar
class MyClass
def self.nesting
Module.nesting
end
def self.parent
nesting[1]
end
end
end
end
parent = Foo::Bar::MyClass.parent
puts "parent of \"Foo::Bar::MyClass\" is \"#{parent}\""
# should probably use Foo::Bar::MyClass.name
# https://gist.github.com/jgaskins/7885999
# https://twitter.com/jamie_gaskins/status/410275628215050240
parent_via_to_s = Foo::Bar::MyClass.to_s.split('::')[0..-2].join('::')
puts "otherwise can always parse to_s which gives us \"#{parent_via_to_s}\""
__END__
Output:
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.3.0]
parent of "Foo::Bar::MyClass" is "Foo::Bar"
otherwise can always parse to_s which gives us "Foo::Bar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment