Guest User

Untitled

a guest
Feb 20th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. class Hash
  2. def find_recursive(&block)
  3. result = catch(:found) do
  4. find do |key, value|
  5. result = value.find_recursive(&block) rescue yield(key, value)
  6. throw(:found, result) if result
  7. end
  8. end
  9. result
  10. end
  11. end
  12.  
  13. class Module
  14. def constant(const)
  15. const = const.to_s.dup
  16. base = const.sub!(/^::/, '') ? Object : ( self.kind_of?(Module) ? self : self.class )
  17. const.split(/::/).inject(base){ |mod, name| mod.const_get(name) }
  18. end
  19.  
  20. def recursive_constants done = []
  21. tree = (constants - done).sort.inject({}) do |tree, const|
  22. mod = const_get(const)
  23. consts = mod.recursive_constants(constants + done) rescue mod
  24. tree[const] = consts
  25. tree
  26. end
  27. tree.empty? ? self.name : tree
  28. end
  29.  
  30. def recursive_const_search(name)
  31. result = recursive_constants.find_recursive do |key, value|
  32. value if key == name.to_s
  33. end
  34. constant(result) rescue nil
  35. end
  36. end
  37.  
  38. module Foo
  39. module Bar
  40. class FooBar
  41. def test
  42. "passed!"
  43. end
  44. end
  45. end
  46. end
  47.  
  48. result = Module.recursive_const_search(:FooBar).new.test rescue "not passed!"
  49. puts result
Add Comment
Please, Sign In to add comment