Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Hash
- def find_recursive(&block)
- result = catch(:found) do
- find do |key, value|
- result = value.find_recursive(&block) rescue yield(key, value)
- throw(:found, result) if result
- end
- end
- result
- end
- end
- class Module
- def constant(const)
- const = const.to_s.dup
- base = const.sub!(/^::/, '') ? Object : ( self.kind_of?(Module) ? self : self.class )
- const.split(/::/).inject(base){ |mod, name| mod.const_get(name) }
- end
- def recursive_constants done = []
- tree = (constants - done).sort.inject({}) do |tree, const|
- mod = const_get(const)
- consts = mod.recursive_constants(constants + done) rescue mod
- tree[const] = consts
- tree
- end
- tree.empty? ? self.name : tree
- end
- def recursive_const_search(name)
- result = recursive_constants.find_recursive do |key, value|
- value if key == name.to_s
- end
- constant(result) rescue nil
- end
- end
- module Foo
- module Bar
- class FooBar
- def test
- "passed!"
- end
- end
- end
- end
- result = Module.recursive_const_search(:FooBar).new.test rescue "not passed!"
- puts result
Add Comment
Please, Sign In to add comment