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?

Community
  • 1
  • 1
Robin
  • 737
  • 2
  • 10
  • 23
  • This is a duplicate of [When monkey patching a method, can you call the overridden method from the new implementation](http://stackoverflow.com/a/4471202/2988). – Jörg W Mittag Jan 19 '13 at 02:43

3 Answers3

8
alias :old_fake_method :fake_method
def fake_method(cmd)
  if (cmd) == "bla"
    puts "caught cmd"
  else
    old_fake_method(cmd)
  end
end
christianblais
  • 2,448
  • 17
  • 14
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.

mbj
  • 1,042
  • 9
  • 19
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)

Dutow
  • 5,638
  • 1
  • 30
  • 40