Ruby:扩展模块的类
我试图定义一个名为“HTML”的类来扩展 Nokogiri - 它使用模块。
我尝试了以下方法:
require 'nokogiri'
class HTML
include Nokogiri
end
但
require 'nokogiri'
class HTML
extend Nokogiri
end
到目前为止,HTML 类不可能继承 nokogiri 中的所有功能。 所以类似的东西不起作用:
doc = HTML.new
doc.HTML(open('http://www.google.com/search?q=tenderlove'))
undefined method `HTML' for # (NoMethodError)
有谁知道我如何能够编写一个继承模块所有方法的类?
I'm trying to to define a class called "HTML" to extend Nokogiri - which uses modules.
I tried the following:
require 'nokogiri'
class HTML
include Nokogiri
end
and
require 'nokogiri'
class HTML
extend Nokogiri
end
but so far it's been impossible that the class HTML inherit of all the functions in nokogiri. So stuff like are not working:
doc = HTML.new
doc.HTML(open('http://www.google.com/search?q=tenderlove'))
undefined method `HTML' for # (NoMethodError)
Does anyone know how I could manage to program a class that inherits of all the methods of a module?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Nokogiri 没有任何可以继承的实例方法:
但通常,您会使用
extend
您想要做的是将 Nokogiri 模块的所有类方法用作您的类的实例方法。 这有点不标准,这就是语法不支持它的原因。 大多数程序员使用 ruby 模块来实现单例模式——只需要一个 Nokogiri,所以其他东西不应该能够使用它的方法。
您可以使用 UndefinedMethods 进行一些黑客攻击来解决这个问题,但考虑到 Nokogiri 在后端有一些编译代码,这可能会产生未定义的错误。
这并不是说您不能将调用转发到 Nokogiri:
这是在 ruby 中实现委托者模式的一种方法(另一种方法是使用 Delegator 类之一)。
Nokogiri doesn't have any instance methods to inherit:
But normally, you would use
extend
What you want to do is use all the class methods of the Nokogiri module as instance methods of your class. Which is a bit nonstandard, which is why the syntax doesn't support it. Most programmers use ruby modules for the Singleton pattern - there only needs to be one Nokogiri, so other things shouldn't be able to use its methods.
You could do some hacking with UndefinedMethods to get around this, but considering that Nokogiri has some compiled code in the backend, this may produce undefined bugs.
Which isn't to say you can't forward calls to Nokogiri:
This is one way to implement the delegator pattern in ruby (another way is to use one of the Delegator classes).