January 2024
Intermediate to advanced
718 pages
20h 15m
English
A hook is a technique that lets you trap some Ruby event, such as object creation. Let’s take a look at some common Ruby hook techniques.
The simplest hook technique in Ruby is to intercept calls to methods in core classes. Perhaps you want to log all the operating system commands your program executes. You could simply use alias_method to rename the system method and replace it with a system method of your own that both logs the command and calls the original Kernel#system method.
For example:
| | class Object |
| | alias_method :old_system, :system |
| | |
| | def system(*args) |
| | old_system(*args).tap do |result| |
| | puts "system(#{args.join(', ')}) returned #{result.inspect}" |
| | |
Read now
Unlock full access