Wrap a method with a macro. Allow for procs to be passed.
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
module Wrapper | |
def wrap(method_name, options: {}) | |
proxy = Module.new | |
proxy.define_method(method_name) do |*args, &block| | |
options = instance_exec(&options) if options.is_a?(Proc) | |
target = is_a?(Module) ? "#{self}." : "#{self.class}#" | |
puts "#{target}#{method_name} is about to be called. `wrap` options #{options}" | |
super *args, &block | |
end | |
self.prepend proxy | |
end | |
end | |
class Thing | |
extend Wrapper | |
wrap :foo, options: -> { foo_options } | |
class << self | |
extend Wrapper | |
wrap :bar, options: -> { bar_options } | |
def bar | |
puts 'Bar!' | |
end | |
private | |
def bar_options | |
{ bar: 2 } | |
end | |
end | |
def foo | |
puts 'Foo!' | |
end | |
private | |
def foo_options | |
{ foo: 1 } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment