Skip to content

Instantly share code, notes, and snippets.

@ttscoff
Created October 9, 2009 18:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ttscoff/206221 to your computer and use it in GitHub Desktop.
Save ttscoff/206221 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# Create an indented, structured CSS skeleton from valid XHTML markup
require 'rubygems'
require 'hpricot'
input = STDIN.read
def recurse_el(el,indent,parentEl)
if el.class == Hpricot::Elem
unless el.name == 'body'
output = ""
output += el.name if el['class']
newParent = el['id'].nil? ? parentEl : "##{el['id']} "
unless el['id'].nil?
output += "##{el['id']}"
parentEl = ""
end
output += el.name if output.empty? && el['class']
output += ".#{el['class']}" if el['class']
newParent = "#{newParent}#{el.name}.#{el['class']} " if el['class']
if output.empty?
puts indent + parentEl + "#{el.name} {}"
else
puts indent + parentEl + output + " {}"
end
indent += " "
end
el.each_child {|el|
recurse_el(el,indent,newParent)
} unless el.children.nil?
end
end
def gather_classes(doc)
classes = []
doc.search("//*[@class]").each {|el|
classes.push(el['class'])
}
puts "\n/* @group classes */\n\n"
classes.uniq.each { |cl|
puts ".#{cl} {}"
}
puts "\n/* @end */"
end
doc = Hpricot(input)
puts <<-ENDRESET
/* @group reset */
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td { margin:0;padding:0; }
table { border-collapse:collapse;border-spacing:0; }
fieldset,img { border:0; }
address,caption,cite,code,dfn,em,strong,th,var { font-style:normal;font-weight:normal; }
ol,ul { list-style:none; }
caption,th { text-align:left; }
h1,h2,h3,h4,h5,h6 { font-size:100%;font-weight:normal; }
q:before,q:after { content:''; }
abbr,acronym { border:0; }
/* @end */
ENDRESET
puts "\n/* @group structure */\n\n"
recurse_el(doc.search("/html/body").first,"","")
puts "\n/* @end */\n\n"
gather_classes(doc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment