Created
October 7, 2012 21:54
-
-
Save begriffs/3849741 to your computer and use it in GitHub Desktop.
Generate Relax Ng template from HTML
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
require 'nokogiri' | |
require 'open-uri' | |
unless [1,2].include? ARGV.length | |
puts "Usage: arrest template-url [css-selector]" | |
exit 1 | |
end | |
def relax node, indent = 0 | |
tab = ' ' | |
pad = tab * indent | |
if ignore node | |
(node.children.map do |c| | |
relax(c, indent) | |
end.select {|k| k != ''}).join(",\n") | |
else | |
if node.name == 'text' | |
result = "#{pad}\"#{node.text().strip}\"" | |
else | |
result = "#{pad}element #{node.name} {\n" | |
kids = [] | |
kids += node.attributes.map do |a| | |
"#{tab}#{pad}attribute #{a[0]} { \"#{a[1].text().strip}\" }" | |
end.select { |k| k != '' } | |
kids += node.children.map do |c| | |
relax(c, indent+1) | |
end.select { |k| k != '' } | |
result << kids.join(",\n") | |
result << "\n" unless kids.empty? | |
result << "#{pad}}" | |
end | |
end | |
end | |
def ignore node | |
%w{html document comment script meta #cdata-section}.include? node.name or | |
(node.name == 'text' and node.text().strip.empty?) | |
end | |
doc = Nokogiri::HTML(open(ARGV[0])) | |
doc = doc.css(ARGV[1]).first if ARGV[1] | |
puts(relax doc) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment