Class: InlineStyle

Inherits:
Object
  • Object
show all
Defined in:
lib/inline-style.rb,
lib/inline-style/rule.rb,
lib/inline-style/version.rb,
lib/inline-style/csspool_wrapper.rb,
lib/inline-style/css_parser_wrapper.rb

Defined Under Namespace

Modules: Mail, Rack Classes: CSSPoolWrapper, CssParserWrapper, Rule

Constant Summary collapse

CSSParser =
if const_defined? :CSSPool
  require 'inline-style/csspool_wrapper'
  CSSPoolWrapper
else
  require 'inline-style/css_parser_wrapper'
  CssParserWrapper
end
VERSION =
'0.5.1'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(html, opts = {}) ⇒ InlineStyle

Returns a new instance of InlineStyle.



29
30
31
32
33
# File 'lib/inline-style.rb', line 29

def initialize html, opts = {}
  @stylesheets_path = opts[:stylesheets_path] || ENV['DOCUMENT_ROOT'] || '.'
  @html           = html
  @dom = String === html ? Nokogiri.HTML(html) : html
end

Class Method Details

.process(html, opts = {}) ⇒ Object

Parameters:

  • html (String, Nokogiri::HTML::Document)

    Html or Nokogiri html to be inlined

  • opts (Hash) (defaults to: {})

    Processing options

Options Hash (opts):

  • :stylesheets_path (String) — default: ENV['DOCUMENT_ROOT']

    Stylesheets root path or app’s public directory where the stylesheets are to be found



25
26
27
# File 'lib/inline-style.rb', line 25

def self.process html, opts = {}
  new(html, opts).process
end

Instance Method Details

#processObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/inline-style.rb', line 35

def process
  nodes_with_rules.each_pair do |node, rules|
    rules = rules.sort_by{ |sel| "#{sel.specificity}%04d" % rules.index(sel) }

    styles = []
    rules.each do |rule|
      next if rule.dynamic_pseudo_class
      rule.declarations.each do |declaration| 
        if defined = styles.assoc(declaration.first)
          styles[styles.index(defined)] = declaration # overrides defined declaration
        else
          styles << declaration
        end
      end
    end

    style = styles.map{ |declaration| declaration.join(': ') }.join('; ') 
    node['style'] = "#{style};" unless style.empty?
  end
  pre_parsed? ? @dom : @dom.to_s
end