How to override class methods

I want to override the Selenium::WebDriver.for method. 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 an error when calling Selenium::Webdriver.for(:phantomjs) .

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

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

+5
source share
2 answers
 module SeleniumWebDriverExtension def for(browser, *args) ... end end Selenium::WebDriver.singleton_class.prepend(SeleniumWebDriverExtension) 
+9
source

When you use self inside the module as follows:

 def self.for(browser, *args) end 

declared as a module function , not a method of an instance of the class that this module will include. This means that it will not appear in the included classes when the module is moved to another class.

This is similar to the entry:

  def SeleniumWebDriverExtension::for end 

So, if you want to call super from a module, declare it as a simple instance method , as the accepted answer suggested. Just wanted to clear you of the reasoning behind this.

Btw SeleniumWebDriverExtension.ancestors to be clear in the inheritance hierarchy.

+4
source

Source: https://habr.com/ru/post/1238223/


All Articles