3

I want to redefine the behavior of a function within a library if certain conditions are met, but execute the original function otherwise. Example:

class LibraryToExtend
  def FunctionToExtend(argument)
    if argument == something
      do_something_new
    else
      do_what_the_function_did_originally
    end
  end
end

I don't think super would work in this instance because I'm overriding the function, not extending it.

sawa
  • 165,429
  • 45
  • 277
  • 381
n s
  • 1,361
  • 2
  • 12
  • 24
  • This is a duplicate of [When monkey patching a method, can you call the overridden method from the new implementation](http://StackOverflow.Com/q/4470108/#4471202). – Jörg W Mittag Jul 04 '11 at 07:55
  • that's no reason to downvote, just close as dup (though I prefer my answer to the 'mile long' answer that question has) – Pablo Fernandez Jul 04 '11 at 14:51

1 Answers1

3

Indeed super wont work. You need to somehow keep a reference to the old method and you do this by creating an alias.

class LibraryToExtend
  alias :FunctionToExtend :original_function
  def FunctionToExtend(argument)
    if argument == something
      do_something_new
    else
      original_function()
    end
  end
end

As a side note, the convention is that ruby methods are in lowecase and underscores (_) not camelcase (but that's just me being bitchy)

Pablo Fernandez
  • 103,170
  • 56
  • 192
  • 232