public
Created

Css inliner using Nokogiri and css_parser

  • Download Gist
inline_css_helper.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.