# Adding code/Extending methods after they have been written?

**URL:** <https://www.ruby-forum.com/t/adding-code-extending-methods-after-they-have-been-written/127245>\
**Category:** Ruby\
**Created:** [January 26, 2008, 10:16pm UTC](https://www.ruby-forum.com/t/adding-code-extending-methods-after-they-have-been-written/127245 "2008-01-26T22:16:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![quik77](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/q/dec6dc/32.png) [@quik77](https://www.ruby-forum.com/u/quik77)\
**Post date:** [January 26, 2008, 10:16pm UTC](https://www.ruby-forum.com/t/adding-code-extending-methods-after-they-have-been-written/127245/1 "2008-01-26T22:16:11Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![quik77](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/q/dec6dc/32.png) [@quik77](https://www.ruby-forum.com/u/quik77)\
**Post date:** [January 26, 2008, 10:27pm UTC](https://www.ruby-forum.com/t/adding-code-extending-methods-after-they-have-been-written/127245/2 "2008-01-26T22:27:21Z")

</div>

> 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.
