Created
September 7, 2018 14:40
-
-
Save maclarensg/8a0954f748556c2dd6128c09440119fe to your computer and use it in GitHub Desktop.
[Ruby - Custom before and after call hooks] Snippet code of how to define and create custom hooks in Ruby #hooks #ruby
This file contains hidden or 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 Hooks | |
@@before_methods = [] | |
@@after_methods = [] | |
def before(*method_names, **actions) | |
# create a Module for preprend to exisitng class | |
to_prepend = Module.new do | |
method_names.each do |method| | |
@@before_methods << method | |
define_method(method) do |*args, &block| | |
send(actions[:do]) if @@before_methods.include? method | |
super(*args,&block) | |
end | |
end | |
end | |
# now the method define in the before will be preprended | |
prepend to_prepend | |
end | |
def after(*method_names, **actions) | |
# create a Module for preprend to exisitng class | |
to_prepend = Module.new do | |
method_names.each do |method| | |
@@after_methods << method | |
define_method(method) do |*args, &block| | |
super(*args,&block) | |
send(actions[:do]) if @@after_methods.include? method | |
end | |
end | |
end | |
# now the method define in the after will be preprended | |
prepend to_prepend | |
end | |
end | |
class Example | |
extend Hooks | |
before :foo, :do => :warning | |
after :bar, :do => :warning | |
def foo | |
puts "in foo" | |
end | |
def bar | |
puts "in bar" | |
end | |
def warning | |
puts "# WARNING" | |
end | |
end | |
o = Example.new | |
o.foo | |
o.bar | |
=begin | |
2.5.1 :034 > o.foo | |
# WARNING | |
in foo | |
=> nil | |
2.5.1 :035 > o.bar | |
in bar | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment