Skip to content

Instantly share code, notes, and snippets.

@savetheclocktower
Created December 17, 2008 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save savetheclocktower/36883 to your computer and use it in GitHub Desktop.
Save savetheclocktower/36883 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'css_parser'
require 'hpricot'
require 'open-uri'
def fix_file(html_input_file, css_input_file, html_output_file, css_output_file)
# Instantiate Hpricot doc object
doc = Hpricot(File.read(html_input_file))
parser = CssParser::Parser.new
parser.load_file!(css_input_file)
css_output = ""
# Iterate over each parsed
parser.each_selector(:screen) do |selector, declarations, specificity|
css_output << "#{fixed_selector(selector)} { #{declarations.to_s} } "
doc.search(selector).each do |element|
element.attributes['class'] += " #{normalized_class_name(selector)}"
end
end
html_output = doc.to_s
File.open(html_output_file, 'w') {|f| f.write(html_output) }
File.open(css_output_file, 'w') {|f| f.write(css_output) }
end
# Transforms '#main div.foo.bar' into '#main div.foo_bar'
def fixed_selector(selector)
selector.gsub(/(?:\.\w+)(?:\.\w+)/) do |subselector|
".#{normalized_class_name(subselector)}"
end
end
def normalized_class_name(selector)
# match two or more consecutive class names
matches = selector.match(/(?:\.(\w+))(?:\.(\w+))/)
class_names = matches.to_a
class_names.shift # pop off the entire string match
class_names.join("_")
end
fix_file("index.html", "main.css", "index_ie6.html", "main_ie6.css")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment