Last active
December 30, 2015 21:09
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Module | |
def namespace | |
path = name.split('::')[0...-1] | |
path.reduce(Object) { |namespace, const| namespace.const_get(const) } | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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