Execute method like before_filter in Rails
metaprogramming, ruby
Solution
You don't need a gem for simple metaprogramming like this. What you can do is redefine the "after" method to call the "before" method and then the original "after" method.
This works even when using `before` multiple times on the same method or when creating a chain of `before` calls.
module MySuperModule
def before meth, opts
old_method = instance_method(meth)
define_method(meth) do
send opts[:call]
old_method.bind(self).call
end
end
end
class MyClass
extend MySuperModule
def foo
puts "foo"
end
def bar
puts "bar"
end
def baz
puts "baz"
end
before :foo, call: :bar
before :bar, call: :baz
end
MyClass.new.foo
# baz
# bar
# foo
Problem
I try to write a metaprogramming for execute a method before 'master' method. Why ? Because, I have several class and it's ugly to repeat the call in the head of the `method` Case : ``` class MyClass include MySuperModule before :method, call: before_method def before_method puts "Before.." end end class SomeClass < MyClass def method puts "Method.." end end module MySuperModule # the awesome code end ``` Output : ``` SomeClass.new.method => "Before.. Method.." ``` So, I try write a module with `ClassMethods`or `method_missing`without success.