Apr14
Extend After
I was faced with a situation not too long ago that forced me to copy and paste a lot of code that did the same thing. It was one line, self.save, but still felt too redundant. Then I realized I was using ruby, so why not let it’s magic powers do it for me? I came up with several implementations but used this one in the end:
module After
def after(*methods, &block)
methods.each do |name|
m = self.instance_method(name).bind(self.new)
define_method name do
instance_exec m.call, &block
end
end
end
end
It could still be more dynamic in the way it calls the methods. You are forced to call after after you define your class methods, when I’d rather call after at the top of the class definition. Maybe I’ll re-implement this some day (or maybe it already exists?) or optionally fork it and help me out.