Skip to content

Instantly share code, notes, and snippets.

@solidiquis
Last active October 14, 2022 21:44
Show Gist options
  • Save solidiquis/ec9af41e5fc1cb982333617f6c45712e to your computer and use it in GitHub Desktop.
Save solidiquis/ec9af41e5fc1cb982333617f6c45712e to your computer and use it in GitHub Desktop.
Ruby instance method before-and-after hooks demo
# quick and dirty demo
class Foo
include(Module.new do
def self.included(including_class)
including_class.extend(StaticMethods)
including_class.prepend(Hooks)
end
module Hooks; end
module StaticMethods
def hook(fn, before: nil, after: nil)
Hooks.define_method(fn) do |*args, **kwargs, &block|
before.call if before
super(*args, **kwargs, &block)
after.call if after
end
end
end
end)
def bar(x, y, a:, b:, &block)
puts a, b
puts x, y
block.call if block_given?
end
hook :bar,
before: -> { puts "before hook" },
after: -> { puts "after hook" }
end
Foo.new.bar(1, 2, a: 1, b: 2)
Foo.new.bar(1, 2, a: 1, b: 2) do
puts "jajaja"
end
# Output:
# before hook
# 1
# 2
# 1
# 2
# after hook
# before hook
# 1
# 2
# 1
# 2
# jajaja
# after hook
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment