Last active
March 21, 2017 12:55
-
-
Save aileron/19a486b167bded00b307df4158a12adb to your computer and use it in GitHub Desktop.
Nokogiri でパースしたオブジェクトの xpath 列挙
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def flatten_attributes | |
objects = {} | |
stack = [] | |
stack << { name: '', object: html.at('body'), children: html.at('body').children.dup } | |
while stack.present? | |
parent = stack.last | |
obj = parent[:object] | |
name = parent[:name] | |
name += obj.name | |
name = "##{obj.attr(:id)}" if obj.attr(:id) | |
name += ".#{obj.attr(:class)}" if obj.attr(:class) | |
unless child = parent[:children].pop | |
next stack.pop | |
end | |
if child.children.length == 1 && child.children.first.text? | |
objects[name] ||= [] | |
objects[name] << child | |
next | |
end | |
stack << { name: "#{name} > ", object: child, children: child.children.dup } | |
end | |
objects | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment