Created
August 3, 2011 07:05
-
-
Save craigmcnamara/1122070 to your computer and use it in GitHub Desktop.
Css inliner using Nokogiri and css_parser
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 '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