Created
August 23, 2024 17:26
-
-
Save aks/3ee867c9503b71a0db9385a380fa2acb to your computer and use it in GitHub Desktop.
Show how class methods can be wrapped to intercept and manage their return values without code changes in their clients.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# show how class methods can be wrapped to intercept and manage their return values without code changes in their clients. | |
class MyClass | |
class << self | |
def method_one | |
"result from method one" | |
end | |
def method_two | |
"result from method two" | |
end | |
end | |
end | |
module Wrapper | |
def report_return_value(klass, method_name) | |
original_method = klass.singleton_method(method_name) | |
define_singleton_method(method_name) do |*args| | |
result = original_method.call(*args) | |
puts "Return value of #{method_name}: #{result}" | |
result | |
end | |
end | |
def wrap_them_all | |
report_return_value(MyClass, :method_one) | |
report_return_value(MyClass, :method_two) | |
end | |
end | |
MyClass.extend Wrapper | |
MyClass.wrap_them_all | |
MyClass.method_one | |
MyClass.method_two |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is what the output looks like: