Skip to content

Instantly share code, notes, and snippets.

@aileron
Last active March 21, 2017 12:55
Show Gist options
  • Save aileron/19a486b167bded00b307df4158a12adb to your computer and use it in GitHub Desktop.
Save aileron/19a486b167bded00b307df4158a12adb to your computer and use it in GitHub Desktop.
Nokogiri でパースしたオブジェクトの xpath 列挙
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