Skip to content

Instantly share code, notes, and snippets.

@depy
Created January 20, 2014 20:54

Revisions

  1. depy created this gist Jan 20, 2014.
    59 changes: 59 additions & 0 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    class MyClass

    def abc(i)
    p "abc"
    p i
    42
    end

    end

    module StreetWalker

    def self.included(base)
    base.extend(self)
    end

    def hook_before(method, clazz, &block)
    temp_method = method.to_s+"_before_hook"
    hook(method, temp_method, clazz, block, nil)
    end

    def hook_after(method, clazz, &block)
    temp_method = method.to_s+"_after_hook"
    hook(method, temp_method, clazz, nil, block)
    end


    private

    def hook(method, temp_method, clazz, before_block, after_block)
    clazz.instance_eval do
    alias_method temp_method, method

    define_method(method) do |*args|
    before_block.call if before_block
    result = send(temp_method, *args)
    after_block.call(result) if after_block
    end
    end
    end
    end

    module MyClassTestHooks

    include StreetWalker

    hook_before :abc, MyClass do |result|
    p "BEFORE!"
    end

    hook_after :abc, MyClass do |result|
    p "AFTER"
    p "Result > "+result.to_s
    end

    end

    v = MyClass.new
    v.abc 1