[英]How to override class methods
I want to override the method Selenium::WebDriver.for
. 我想重写方法
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. 但是当调用
Selenium::Webdriver.for(:phantomjs)
时出现错误。
NoMethodError: super: no superclass method `for' for Selenium::WebDriver::Driver:Class
How can I call the original method from the overriding method? 如何从重写方法调用原始方法?
module SeleniumWebDriverExtension
def for(browser, *args)
...
end
end
Selenium::WebDriver.singleton_class.prepend(SeleniumWebDriverExtension)
When to you use self
inside a module like this: 什么时候在这样的模块中使用
self
:
def self.for(browser, *args)
end
it is declared as a module function
, not an instance method on the class that will include this module. 它被声明为
module function
,而不是包含此模块的类上的实例方法。 What this means is that won't appear on included classes when the module is mixed into another class. 这意味着当模块混合到另一个类时,它不会出现在包含的类中。
It is similar to writing: 它与写作类似:
def SeleniumWebDriverExtension::for
end
So if you want to call super
from within the module, declare it as a simple instance method
like the accepted answer has suggested. 因此,如果您想从模块中调用
super
,请将其声明为一个简单的instance method
就像接受的答案所建议的那样。 Just wanted to clear you on the reasoning behind this. 只是想清楚你背后的原因。
Btw SeleniumWebDriverExtension.ancestors
to be clear on the inheritance hierarchy. 顺便说一下
SeleniumWebDriverExtension.ancestors
在继承层次结构上要清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.