Ruby Hooks

How to define and create custom hooks in Ruby

25

Votes

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

Vote Here

You must earn at least 1 vote on your snippets to be allowed to vote

Terms Of Use

Privacy Policy

Featured snippets are MIT license

Gears & Masters

Advertise

DevOpsnipp.com © 2020

medium.png