Skip to content

Instantly share code, notes, and snippets.

@fguillen
Last active May 19, 2019 05:55
Show Gist options
  • Save fguillen/bac172d48b73148ca911c0fed2a03953 to your computer and use it in GitHub Desktop.
Save fguillen/bac172d48b73148ca911c0fed2a03953 to your computer and use it in GitHub Desktop.
Providing an `around_action` like functionality in arbitrary Ruby classes
module MyWrapperCreator
def my_method_wrapper(method_name)
original_method = instance_method(method_name)
define_method(method_name) do |*args, &block|
puts "wrapper :: INI"
result = original_method.bind(self).call(*args, &block)
puts "wrapper :: END"
result
end
end
end
class MyClass
# Trigger the method wrapper in an instance method
extend MyWrapperCreator
def my_instance_method(params)
puts "MyClass.my_instance_method"
"RESULT: #{params}"
end
my_method_wrapper(:my_instance_method)
# Trigger the method wrapper in a class method
def self.my_class_method(params)
puts "MyClass.my_class_method"
"RESULT: #{params}"
end
class << self
extend MyWrapperCreator
my_method_wrapper(:my_class_method)
end
end
module MyModule
def self.my_class_method(params)
puts "MyModule.my_class_method"
"RESULT: #{params}"
end
# Trigger the method wrapper in a class method
class << self
extend MyWrapperCreator
my_method_wrapper(:my_class_method)
end
end
puts "Class instance method"
puts MyClass.new.my_instance_method("params")
puts
puts "Class class method"
puts MyClass.my_class_method("params")
puts
puts "Module class method"
puts MyModule.my_class_method("params")
puts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment