Create a gist now

Instantly share code, notes, and snippets.

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