CSC/ECE 517 Summer 2008/wiki1 5 bk: Difference between revisions
Line 5: | Line 5: | ||
*Debugging problematic code. | *Debugging problematic code. | ||
==Example of a Hook== | ==Example of a Hook== | ||
<code>module Kernel | <code>module Kernel</code> | ||
alias_method :original_system, :system | alias_method :original_system, :system | ||
def system(*args) | def system(*args) | ||
Line 14: | Line 14: | ||
end | end | ||
end | end | ||
system("ls -al") | system("ls -al") | ||
Your program executed the "ls -al" command. | Your program executed the "ls -al" command. | ||
It was executed at: Mon Jun 2 21:19:27 EDT 2008 | It was executed at: Mon Jun 2 21:19:27 EDT 2008 | ||
Line 25: | Line 25: | ||
-rw-r--r-- 1 brking brking 235 2008-06-02 20:29 hooking.rb | -rw-r--r-- 1 brking brking 235 2008-06-02 20:29 hooking.rb | ||
-rw-r--r-- 1 brking brking 287 2008-06-02 21:19 moreHooking.rb | -rw-r--r-- 1 brking brking 287 2008-06-02 21:19 moreHooking.rb | ||
===Example of a Hook 2=== | ===Example of a Hook 2=== | ||
==Understanding Aspect Oriented Programming== | ==Understanding Aspect Oriented Programming== |
Revision as of 16:07, 3 June 2008
Understanding Hooks
The hooking mechanism in Ruby allows certain functional events inside a running program to be identified while providing an action that will occur upon detection of the specified event. In this way, hooks serve as a detector of actions within the code. Examples of where such a technique would prove useful include:
- Recording when or how many times a method is called.
- Recording when an object is created.
- Debugging problematic code.
Example of a Hook
module Kernel
alias_method :original_system, :system def system(*args) puts "Your program executed the \"#{args.join(', ')}\" command." puts "It was executed at: " + `date` puts "The command output the following: " original_system(*args) end
end system("ls -al")
Your program executed the "ls -al" command. It was executed at: Mon Jun 2 21:19:27 EDT 2008 The command output the following: total 20 drwxr-xr-x 2 brking brking 4096 2008-06-02 21:19 . drwxr-xr-x 18 brking brking 4096 2008-06-02 21:19 .. -rw-r--r-- 1 brking brking 134 2008-06-01 22:01 fib.rb -rw-r--r-- 1 brking brking 235 2008-06-02 20:29 hooking.rb -rw-r--r-- 1 brking brking 287 2008-06-02 21:19 moreHooking.rb