Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Last active December 30, 2015 21:09
Show Gist options
  • Save jgaskins/7885999 to your computer and use it in GitHub Desktop.
Save jgaskins/7885999 to your computer and use it in GitHub Desktop.
Ruby nested modules/classes figuring out their namespace (edited to work with Ruby < 2.0)
class Module
def namespace
path = name.split('::')[0...-1]
path.reduce(Object) { |namespace, const| namespace.const_get(const) }
end
end
module A
module B
module C
end
end
end
describe Module do
it 'knows its parent' do
A::B::C.namespace.should be A::B
A::B.namespace.should be A
A.namespace.should be Object
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment