Getting what was added upon load

Deadly 提交于 2019-12-08 06:26:22

问题


Is there a way to get the list (array) of all the constants (including modules and classes) and their methods and class or instance variables that are added or redefined upon loading an external ruby file?


回答1:


This should do the trick:

def all_constants_with_methods
  constants = Object.constants.map { |sym| Object.const_get sym }
  Hash[constants.map { |constant| [constant, (constant.instance_methods rescue [])] }]
end

before = all_constants_with_methods
load foo.rb
after = all_constants_with_methods

constants_added = after.keys - before.keys
methods_added = Hash[after.keys.map do |c|
                       [c, after[c] - (before[c] || [])]
                     end.reject do |_, v|
                       v.empty?
                     end]

There's no way that I know of to know if a method was redefined, though. You can easily expand this to class variables (using class_variables) and class instance variables (using instance_variables).



来源:https://stackoverflow.com/questions/12737792/getting-what-was-added-upon-load

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!