Adding code/Extending methods after they have been written?

Hi there,

Let’s say i have 10 methods. Each one looks like so:

def p(some_input)
print some_input

do some more stuff…

end

Some months after I wrote this, I realized that I need to
handle blocks given to these methods. (Need is the wrong
word, a better word would be i want to because
Ruby allows you to)

I do it like so currently:

if block_given?
yield
some_mandatory_finalizer_method
end

The thing actually is… The last 4 lines of code look
like repetitive boilerplate code to me. The way I solved it
was by copy pasting this segment into each method, but
it kinda does not feel clean. (I have even put these
four lines of code into one line, so that I have
an easier time to remove this code if i can think of a
cleaner solution)

Does anyone else of you know of a way to add “code rules”
to some methods? Something like this would be cool:

def add_boilerplate_code
if block_given?
yield
some_mandatory_finalizer_method # this is always the same method
end
end

METHODS_THAT_NEED_TO_BE_EXTENDED = %w( p q r s t u v w x y z )
METHODS_THAT_NEED_TO_BE_EXTENDED.each do |my_method|
my_method.add_boilerplate_code
end

Thankful for any tips!

Does anyone else of you know of a way to add “code rules”
to some methods? Something like this would be cool:

Looks like a good use case for Aspect oriented programming.
AOP frameworks provide mechanisms to do exactly that.
There are (at least) two AOP frameworks on RubyForge:
aspectr and aquarium.

Otherwise it’s fairly easy to create such a facility
from scratch via alias_method.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs