簡體   English   中英

class << self,alias_method和monkey patching Mechanize :: Cookie

[英]class << self, alias_method, and monkey patching Mechanize::Cookie

我有一個問題與Mechanize :: Cookie行為不端,我想嘗試修補它。 我的代碼:

class Mechanize::Cookie
  class << self; alias_method :old_parse, :parse end
  def self.parse(uri, str, log = Mechanize.log)
    puts 'new parse!'
    #str.gsub!(/domain[^;]*;/,'')
    old_parse(uri, str, log)
  end
end

當我添加它時,cookie不會被添加,我無法弄清楚原因。

編輯:要查看問題,請嘗試使用和不使用猴子補丁的此代碼:

agent = Mechanize.new
agent.get 'http://www.google.com/'
pp agent.cookie_jar

沒有補丁,你會看到一個完整的餅干罐,它是空的。

yield cookie if block_given?看起來原始的解析方法有一個yield cookie if block_given? 聲明。 你也需要能夠傳遞一個塊。

編輯:

更清楚......

class Foo
    def self.x
        yield "yielded from x!" if block_given?
    end
end

class Foo
    class <<self
        alias :y :x
    end
    # new implementation of x's last parameter is an optional block
    def self.x(&block) 
        puts "in redefined x."
        puts "block=#{block}"
        self.y(&block) #use the block as the last parameter 
    end
end

Foo.x{|value| puts "value is '#{value}'"}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM