ruby-on-rails - 为什么此方法无法检测 ActionView::Template :render?

标签 ruby-on-rails ruby ruby-on-rails-3 metaprogramming mvc-mini-profiler

我们正在移植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/

相关文章:

ruby-on-rails - Rails和回形针,删除记录但不删除附件

ruby-on-rails - 如何完全删除 ruby​​gems 和 rails 等

ruby-on-rails - 在 Rails 3 中通过关联使用 has_many 防止孤立对象

ruby - 使用数组作为 ruby​​ 哈希键的用例

ruby - 将 SitePrism 与 Rspec 和 Capybara 功能规范一起使用

ruby - NameError(未初始化常量 ActionDispatch::ExceptionWrapper):

ruby-on-rails - 使用 Rails link_to 来发布链接

ruby-on-rails - 使用 Guard 和 Spork 重新加载 RSpec 共享示例

ruby-on-rails - 是否可以使用 Haml 生成普通的 XML?

ruby-on-rails - 无方法错误 : undefined method `email' for nil:NilClass : can't send email with devise/sendgrid(Rails 3. 2)