How to override a method of a ruby gem for certain conditions?

Sridhar

New Member
#1
I am trying to override one of the private methods of a gem only when certain conditions are met.

I would like to use this method only if a certain condition is met else use the gem's method.
Mã:
module Net
  class FTP
    def makepasv
      if condition
        @sock.peeraddr[0] == 'AF_INET' ? parse229(sendcmd('EPSV')) : parse227(sendcmd('EPSV'))
      else
        super
      end
    end
  end
end
 

Admin

Administrator
Thành viên BQT
#2
You can prepend the class being overriden and then use the conditional. This way your module will be the last in the ancestors chain and will be able to call super in order to use default behaviour

e.g.
Mã:
module Override
  def to_s(*)
    if self == 'a'
      "===a==="
    else
      super
    end
  end
end
String.prepend(Override)

[9] pry(main)> String.new("a")
=> "a"                                                                                                           
[10] pry(main)> String.new("a").to_s
=> "===a==="
[11] pry(main)> String.new("b").to_s
=> "b"
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top