Search code examples
rubyoverridingclass-methodprepend

How to override class methods


I want to override the method Selenium::WebDriver.for. This is what I tried:

module SeleniumWebDriverExtension
  def self.for(browser, *args)
    if browser != :phantomjs
      super(browser, *args)
    else
      options = {
          "phantomjs.cli.args" => ["--ssl-protocol=tlsv1"]
      }
      capabilities = Selenium::WebDriver::Remote::Capabilities.phantomjs(options)
      super(browser, desired_capabilities: capabilities)
    end
  end
end

Selenium::WebDriver.prepend(SeleniumWebDriverExtension)

But I got error when Selenium::Webdriver.for(:phantomjs) is called.

NoMethodError: super: no superclass method `for' for Selenium::WebDriver::Driver:Class

How can I call the original method from the overriding method?


Solution

  • module SeleniumWebDriverExtension
      def for(browser, *args)
        ...
      end
    end
    
    Selenium::WebDriver.singleton_class.prepend(SeleniumWebDriverExtension)