ruby脚本的默认回调是什么?

时间:2014-03-26 13:36:23

标签: ruby

我刚刚发现了我的ruby脚本的默认回调:at_exit - 非常酷。

我如何找到这样的其他默认回调?如果我知道如何找到Ruby附带的所有默认回调,我想我可以编写一些更灵活/更强大的ruby代码。

2 个答案:

答案 0 :(得分:5)

修改根据JörgWMittag的评论添加了一些更正。

它们被广泛称为 hooks (可能来自emacs lisp的影响)。除at_exit之外,这是我认为全面的Ruby钩子列表:

set_trace_func
initialize
method_missing
singleton_method_added
singleton_method_removed
singleton_method_undefined
respond_to_missing?
extended
included
method_added
method_removed
method_undefined
const_missing
inherited
intitialize_copy
intitialize_clone
intitialize_dup
prepend
append_features
extend_features
prepend_features

答案 1 :(得分:1)

使用Ruby 2.0.0,TracePoint类将在这方面帮助您,非常具体。它会告诉你究竟什么是为任何特定代码调用的钩子:

示例:

trace = TracePoint.new(:c_call) do |tp|
  p [tp.lineno, tp.event, tp.defined_class,tp.method_id]
end

trace.enable do
  class Foo # line num 6
    def bar # line num 7
      12
    end
    def self.baz # line num 10
      13
    end
  end
  Foo.new.bar # line num 14
  Foo.baz
end
# >> [6, :c_call, Class, :inherited]
# >> [7, :c_call, Module, :method_added]
# >> [10, :c_call, BasicObject, :singleton_method_added]
# >> [14, :c_call, Class, :new]
# >> [14, :c_call, BasicObject, :initialize]