开发者

Redefining a method [duplicate]

开发者 https://www.devze.com 2023-03-17 14:11 出处:网络
This question already has answers here: When monkey patching an instance method, can you call the开发者_StackOverflow overridden method from the new implementation?
This question already has answers here: When monkey patching an instance method, can you call the开发者_StackOverflow overridden method from the new implementation? (3 answers) Closed 8 years ago.

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.


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号