Skip to content

Instantly share code, notes, and snippets.

@dudo
Last active June 30, 2021 04:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dudo/ed54989bc83762ba44dfad71fb7bd790 to your computer and use it in GitHub Desktop.
Save dudo/ed54989bc83762ba44dfad71fb7bd790 to your computer and use it in GitHub Desktop.
Wrap a method with a macro. Allow for procs to be passed.
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