Sha256: f7bc2e2971f2901397c5b2e3f98f1f17ea6500285b1d6c1279fb5ece49f90f9f

Contents?: true

Size: 1.02 KB

Versions: 3

Compression:

Stored size: 1.02 KB

Contents

require 'nokogiri'
require 'css_parser'

module SexxyEmails::Css
  include CssParser

  class << self
    # Takes a string of HTML and inlines any css blocks in it.
    def inline(html, options = {})
      Nokogiri::HTML(html).tap do |doc|
        css_parser = CssParser::Parser.new
        # Collect the style and remove from the html tree
        doc.css('style').each do |style|
          css_parser.add_block!(style.content)
          style.remove
        end

        # Each selector
        css_parser.each_selector do |selector, declaration|
          doc.css(selector).each do |node|
            node['style'] = merge_rules(node, selector, declaration)
          end
        end
      end.to_s
    end

    protected
    # Let existing styles be at the top of the cascade
    def merge_rules(node, selector, declaration)
      if node['style'].nil?
        declaration
      else
        CssParser.merge(
          RuleSet.new(nil, declaration), 
          RuleSet.new(nil, node['style'])).declarations_to_s
      end
    end

  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
sexxy-emails-0.0.3 lib/sexxy_emails/css.rb
sexxy-emails-0.0.2 lib/sexxy_emails/css.rb
sexxy-emails-0.0.1 lib/sexxy_emails/css.rb