2

私たちはMiniProfilerを Ruby に移植しており、Rails ビューとパーシャルの自動計測を追加したいと考えていました。

私は既存のインストルメンテーションサポートを認識していますが、理想的には「開始」イベントと「停止」イベントを取得したいと考えています。また、通知をサポートしていない以前のバージョンの 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 (nil:NilClass に対して未定義のメソッド `html_safe')

このメソッド フックの何が問題になっていますか? メソッドをフックしてこの問題に脆弱にならないようにするための適切で堅牢な方法は何ですか (簡単な API を維持する: prof klass, method)

4

1 に答える 1

2

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
于 2012-04-13T05:03:36.800 に答える