【问题标题】:Proper Monkey Patching Using Modules in Ruby在 Ruby 中使用模块进行适当的猴子修补
【发布时间】:2017-06-30 06:12:36
【问题描述】:

我想为硒红宝石制作猴子补丁。

这是我关注的article

但是,当我定义自己的代码时:

module Selenium
  module WebDriver
    module Driver
      module CookieManagement
        # This is the same as Driver.get, but I just want it to save all the domains it goes to in an easily accessible variable
        def get_and_save(url)
          puts "You've asked me to get, so I am getting"
          get(url)
        end
      end
    end
  end
end

我收到一个错误:

Uncaught exception: Driver is not a module

我知道发生这种情况是因为我已经定义了一个 Driver 类,所以没关系。但是,文章中的这个家伙怎么不会发生这种情况,更重要的是,那么可接受的解决方法是什么?

更新

我想我不包括我确实包含导致上述错误的代码行是不好的。

Selenium::WebDriver::Driver.include Selenium::WebDriver::Driver::CookieManagement

而且,它是纯红宝石。 不涉及轨道。

【问题讨论】:

  • “驱动程序不是一个模块”——它是一个类,见the source
  • @wiesion 是的,我可以看到,正如我上面所说的。因此,我的问题。这家伙做了完全相同的事情并写了一篇关于它的文章。它对他有用,我不明白为什么。
  • 文章提到你应该在自定义文件和{Target}.include(寻找评论# Actually monkey-patch DateTime)中组织你的Monkey补丁。这是他唯一一次提到它,但这是一个要求。
  • 在您的情况下,您应该将猴子补丁放在/lib/core_extensions/selenium/web_driver/driver/cookie_management.rb 和初始化程序中(确保此时已加载 Selenium)在目标类/模块上执行包含。您也可以查看this post
  • 你说的“为什么文章里的那个家伙没有发生”是什么意思?他在文章的什么地方定义了Selenium::WebDriver::Driver 模块?

标签: ruby


【解决方案1】:

好的,所以使用这个答案When monkey patching a method, can you call the overridden method from the new implementation?

我想出了:

require 'selenium-webdriver'

module CookieManagement
  def get_and_save(url)
    puts "You told me to get, so I am getting"
    get(url)
  end
end


class Selenium::WebDriver::Driver
  include CookieManagement
end

然后我 require_relative 而不是 .rb 文件中需要该功能的标准 selenium-webdriver gem。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 2019-08-06
    • 2011-04-19
    相关资源
    最近更新 更多