Skip to content

Instantly share code, notes, and snippets.

@craigmcnamara
Created August 3, 2011 07:05
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 craigmcnamara/1122070 to your computer and use it in GitHub Desktop.
Save craigmcnamara/1122070 to your computer and use it in GitHub Desktop.
Css inliner using Nokogiri and css_parser
require 'nokogiri'
require 'css_parser'
module InlineCSSHelper
include CssParser
# Takes a string of HTML and inlines any css blocks in it.
def inline_css(message)
css_parser = CssParser::Parser.new
doc = Nokogiri::HTML(message)
# Collect the style and remove from the html tree
doc.css('style').each_with_index do |style, i|
css_parser.add_block!(style.content)
style.remove
end
css_parser.each_selector do |selector, declaration|
# Each selector
doc.css(selector).each do |node|
# On to each element, let existing styles be at the top of the cascade
node['style'] = node['style'].nil? ?
declaration : CssParser.merge(RuleSet.new(nil, declaration), RuleSet.new(nil, node['style'])).declarations_to_s
end
end
doc
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment