繁体   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