是否可以在Ruby中的每一行之后运行代码? [英] Is it possible to run code after each line in Ruby?

查看:61
本文介绍了是否可以在Ruby中的每一行之后运行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以在ruby中用前和后钩子修饰方法,但是是否可以对给定方法的每一行进行修饰?

例如,我有一个自动化测试,我想验证每个步骤之后页面上没有显示错误.该错误显示为红色div,并且对于Ruby来说raise或类似的符号均不可见,因此我必须手动进行检查(还有其他一些用例).

我了解使用set_trace_func是可能的.但是我认为,这可能带来更多的问题,而不是带来更多的好处,因为它适用于整个调用树(并且需要我自己对其进行过滤).

更新(说明):

我有兴趣拦截在给定方法内 执行的所有动作(或调用).这意味着调用了未指定数量的类,因此我不能仅拦截任何给定的类/方法集.

解决方案

听起来您想跟踪 every 对象上的 every 方法调用,但仅在跨度期间跟踪每次调用 one specific 方法的次数.在这种情况下,您可以重新定义打开和关闭仪器的方法.首先,使用 解决方案

It sounds like you want tracing on every method call on every object, but only during the span of every call to one particular method. In that case, you could just redefine the method to turn on- and off instrumentation. First, use the universal instrumentation suggsted in Pinochle's answer, then redefine the method in question as follows:

# original definition, in /lib/foo.rb:
class Foo
  def bar(baz)
    do_stuff
  end
end

# redefinition, in /test/add_instrumentation_to_foo.rb:
Foo.class_eval do
  original_bar = instance_method(:bar)
  def bar(baz)
    TracedObject.install!
    original_bar.bind(self).call(baz)
    TracedObject.uninstall!
  end
end

You'd need to write the install! and uninstall methods, but they should be pretty trivial: just set or unset a class variable and check for it in the instrumentation logic.

这篇关于是否可以在Ruby中的每一行之后运行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆