Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

metaprogramming - Is it possible to run code after each line in Ruby?

I understand that it is possible to decorate methods with before and after hooks in ruby, but is it possible to do it for each line of a given method?

For example, I have an automation test and I want to verify that after each step there no error shown on the page. The error is shown as a red div and is not visible to Ruby as raise or anything like that, so I have to check for it manually (there are several other use cases as well).

I understand that it might be possible using set_trace_func. But I think this may bring more problems than benefits since it works over entire call tree (and requires me to filter it myself).

UPDATE (clarification):

I am interested in intercepting all actions (or calls) that are performed within a given method. This means unspecified number of classes is called, so I can't just intercept any given set of classes/methods.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is, and you can get a full description of how to do it in section 8.9 of The Ruby Programming Language. Running the code on each invocation of the method involves sending the method to a TracedObject class that has an implementation for method_missing. Whenever it receives a message, it invokes method_missing and executes whatever code you have assigned to it. (This is, of course, for general tracing).

That's the general description of the procedure for doing it, you can consult the book for details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...