Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redefining a method [duplicate]

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.

like image 361
n s Avatar asked Dec 09 '25 03:12

n s


1 Answers

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)

like image 174
Pablo Fernandez Avatar answered Dec 10 '25 17:12

Pablo Fernandez