我们正在移植MiniProfiler到 Ruby 并希望为 Rails View 和部分添加自动检测。
我知道 existing instrumentation支持,但理想情况下希望获得“开始”和“停止”事件。我们还希望支持没有通知支持的早期版本的 Rails。
我编写了一个简短的仪器,并测试了在之前和之后调用中连接渲染:
def prof(klass, method)
with_profiling = (method.to_s + "_with_profiling").intern
without_profiling = (method.to_s + "_without_profiling").intern
klass.send :alias_method, without_profiling, method
klass.send :define_method, with_profiling do |*args, &orig|
puts "before #{method} #{args}"
self.send without_profiling, *args, &orig
puts "after #{method}"
end
klass.send :alias_method, method, with_profiling
end
prof ActionView::Template, :render
但是,一旦激活此功能,render
就无法正确检测。特别是这适用于某些部分,但会爆炸:
ActionView::Template::Error (undefined method `html_safe' for nil:NilClass)
这个方法钩子(Hook)有什么问题?什么是 Hook 方法的正确稳健方法,以便它们不易受到此问题的影响(维护简单的 API:prof klass,方法
)
最佳答案
您已重新定义了返回最终 puts
结果的方法,该结果通常为 nil
。修复可能是:
klass.send :define_method, with_profiling do |*args, &orig|
puts "before #{method} #{args}"
result = self.send without_profiling, *args, &rig
puts "after #{method}"
result
end
关于ruby-on-rails - 为什么此方法无法检测 ActionView::Template :render?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10135147/