# Method mixin?

**URL:** <https://www.ruby-forum.com/t/method-mixin/193585>\
**Category:** Ruby\
**Created:** [August 20, 2010, 3:03am UTC](https://www.ruby-forum.com/t/method-mixin/193585 "2010-08-20T03:03:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![opti900](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/bc8723/32.png) [@opti900](https://www.ruby-forum.com/u/opti900)\
**Post date:** [August 20, 2010, 3:03am UTC](https://www.ruby-forum.com/t/method-mixin/193585/1 "2010-08-20T03:03:11Z")

</div>

Just wonder is there any way to inject a bunch of code into an instance  
method, just like how a module can be used as a mixin to a class?

---

<div class="post-metadata">

**Author:** ![opti900](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/bc8723/32.png) [@opti900](https://www.ruby-forum.com/u/opti900)\
**Post date:** [August 20, 2010, 7:46am UTC](https://www.ruby-forum.com/t/method-mixin/193585/2 "2010-08-20T07:46:30Z")

</div>

On 20.08.2010 03:03, Cnm C. wrote:

> Just wonder is there any way to inject a bunch of code into an instance  
> method, just like how a module can be used as a mixin to a class?

One thing you can do is alias the original and use it.

class Foo  
def bar; puts 123; end  
end

f = Foo.new  
f.bar

class Foo  
alias \_bar bar

def bar  
puts “before”  
x = \_bar  
puts “after”  
x  
end  
end

f.bar

I once did some meta programming to nicely declare before and after code  
but that code was never production ready. IIRC others did similar  
things.

Kind regards

robert
