1

我有一個機械化:: Cookie行爲不當的問題,我想嘗試猴子修補它。 我的代碼:class << self,alias_method和monkey patching 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 

當我添加這個,餅乾沒有得到補充,我想不通爲什麼。

編輯: 要看到問題,試試這個代碼和沒有猴子補丁:

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

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

+0

是否打印出來? –

+0

是的,「新解析!」打印出來,我可以告訴old_parse也被調用,因爲我在那裏放了一個'puts'行來檢查它。但是,當我包含這些代碼時,Cookie不會被保存。 – pguardiario

+0

當你不包含代碼時,cookie被保存了,對嗎? –

回答

4

看起來像原始分析方法中有一個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}'"} 
+0

謝謝z5h,我認爲這是正確的答案。如果有的話,我可以使用另一個提示。 – pguardiario

+0

就是這樣。謝謝! – pguardiario

相關問題