Method mixin?

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?

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

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