2

Possible Duplicate:
When monkey patching a method, can you call the overridden method from the new implementation?

So I wish to simply add some conditional checks to a method by overriding it, but then I want the original method to be called. How does one do this in ruby?

ie.

method exists

def fakeMethod(cmd) puts "#{cmd}" end 

and I want to add

if (cmd) == "bla" puts "caught cmd" else fakeMethod(cmd) end 

Any ideas?

1

3 Answers 3

8
alias :old_fake_method :fake_method def fake_method(cmd) if (cmd) == "bla" puts "caught cmd" else old_fake_method(cmd) end end 
Sign up to request clarification or add additional context in comments.

Comments

2

Why not use inheritance. It is a classical example overridden methods are augmented with additional logic:

class Foo def foo(cmd) puts cmd end end class Bar < Foo def foo(cmd) if cmd == "hello" puts "They want to say hello!" else super end end end Foo.new.foo("bar") # => prints "bar" Bar.new.foo("hello") # => prints "They want to say hello" 

Sure, this solution only works if you have a chance to instantiate a subclass instance.

Comments

0

There is alias_method_chain and alias_method in ruby for this.

(alias_method_chain is not in ruby, but in ActiveSupport::CoreExtensions, so you minght need to require that if this isn't a rails application)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.