I am new to ruby
Trying to write an around aspect. My code is as follows
My code looks as follows
module Utils
module Aspects
def self.included(base)
base.extend(self)
end
def around_aspect(method_name, before_proc, after_proc)
code = %Q[
def #{method_name} *args, &block
#{before_proc.call}
old_#{method_name} *args, &block
#{after_proc.call}
end
]
class_eval %Q[
alias_method :old_#{method_name}, :#{method_name}
]
class_eval code
end
# def before_aspect method_name, before_proc
# around_aspect method_name, before_proc, ->(){}
# end
#
# def after_aspect method_name, after_proc
# around_aspect method_name, ->(){}, after_proc
# end
end
end
class Test
include Utils::Aspects
def test
puts 'test'
end
before = ->(){puts 'before'}
after = ->(){puts 'after'}
around_aspect :test,before,after
end
Test.new.test
The problem is that when i do Test.new.test
I expect it to print
before, test and after" in order. But right now it prints "before,after and test"
No, it doesn't. When calling
Test.new.test
it only printstest
.before
andafter
are printed when defining the wrapped method, i.e. when callingaround_advice
.Try to put a
puts
in between the call toaround_advice
and the call toTest.new.test
(and try to calltest
several times) to observe this:You are calling the lambdas only once, when defining the method:
You need to call them every time when calling the method:
However, it would be much easier to just use
Module#prepend
, after all, that's what it's there for: