Skip to content

Instantly share code, notes, and snippets.

@aks
Created August 23, 2024 17:26
Show Gist options
  • Save aks/3ee867c9503b71a0db9385a380fa2acb to your computer and use it in GitHub Desktop.
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.
# 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
@aks
Copy link
Author

aks commented Aug 23, 2024

This is what the output looks like:

$ ruby method_wrapper.rb
Return value of method_one: result from method one
Return value of method_two: result from method two

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment