在 Rails 应用程序中扩展 nokogiri
我按如下方式扩展了 Nokogiri::HTML:Document 类以添加名为 on_same_line? 的函数?
module Nokogiri
module HTML
class Document
def on_same_line?(node1,node2,font_sizes)
return false if node1.nil? or node2.nil? or font_sizes.nil?
return false if (node1.name != "div" || node2.name != "div")
fsize1 = font_sizes[node1.children[0].children[0].attributes["class"].value]
fsize2 = font_sizes[node2.children[0].children[0].attributes["class"].value]
style1 = node1.attributes["style"].value
style2 = node2.attributes["style"].value
top1 = style1.split(/;/)[1].split(/:/)[1].to_i
top2 = style2.split(/;/)[1].split(/:/)[1].to_i
(top1 + fsize1 - top2 - fsize2).abs < 4
end
end
end
end
我将此代码放置在我的 Rails 3 应用程序树中位于 lib/nokogiri/html/document.rb 的文件中
我按如下方式调用此函数
if @html_doc.on_same_line?(node,node2,font_size_hash)
### do something
end
此代码位于我创建的单独的自定义 ruby 类中。该类是 MyClass,位于 MyModule 中。此类的代码位于 lib/my_module/my_class.rb 下。
现在,当此代码作为我的 Rails 应用程序的一部分执行时,出现以下错误。
unexpected '?' after '[#<Nokogiri::CSS::Node:0x00000100dfebd8 @type=:ELEMENT_NAME, @value=["on_same_line"]>]'
我不知道为什么会发生这种情况。有人可以帮助我
吗另外,当我在 Rails 应用程序之外运行相同的代码时,我没有收到任何错误,并且它按预期工作
谢谢 保罗
I extended the Nokogiri::HTML:Document class as follows to add a function called on_same_line?
module Nokogiri
module HTML
class Document
def on_same_line?(node1,node2,font_sizes)
return false if node1.nil? or node2.nil? or font_sizes.nil?
return false if (node1.name != "div" || node2.name != "div")
fsize1 = font_sizes[node1.children[0].children[0].attributes["class"].value]
fsize2 = font_sizes[node2.children[0].children[0].attributes["class"].value]
style1 = node1.attributes["style"].value
style2 = node2.attributes["style"].value
top1 = style1.split(/;/)[1].split(/:/)[1].to_i
top2 = style2.split(/;/)[1].split(/:/)[1].to_i
(top1 + fsize1 - top2 - fsize2).abs < 4
end
end
end
end
I placed this code in a file located at lib/nokogiri/html/document.rb in my rails 3 application tree
I call this function as follows
if @html_doc.on_same_line?(node,node2,font_size_hash)
### do something
end
This code is in a separate custom ruby class that I created. This class is MyClass and is in MyModule. The code for this class is placed under lib/my_module/my_class.rb
Now when this code is executed as part of my rails application, I get the following error.
unexpected '?' after '[#<Nokogiri::CSS::Node:0x00000100dfebd8 @type=:ELEMENT_NAME, @value=["on_same_line"]>]'
I have no idea why this is happening. Could someone please help me
Also when I run this same code outside the rails app, I dont get any errors, and it works as expected
Thanks
Paul
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 Rails 3 中,您需要将猴子补丁代码放在 config/initializers 下,而不是放在 lib 下
In rails 3 you need to put your monkey patch code under config/initializers instead of under lib