Class: CSSInliner::Inliner

Inherits:
Object
  • Object
show all
Defined in:
lib/css_inliner/inliner.rb

Instance Method Summary collapse

Constructor Details

#initialize(document, basedir) ⇒ Inliner

Returns a new instance of Inliner.

Parameters:

  • document (Nokogiri::XML::Document)
  • basedir (String)


10
11
12
13
14
# File 'lib/css_inliner/inliner.rb', line 10

def initialize(document, basedir)
  @document = document
  @basedir = basedir
  @extractor = Extractor.new @document, @basedir
end

Instance Method Details

#inlineObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/css_inliner/inliner.rb', line 16

def inline
  original_styles = {}
  @document.search('.//*[@style]').each do |elem|
    original_styles[elem] = elem['style']
    elem.remove_attribute('style')
  end

  css = @extractor.extract
  css.sorted_selectors.each do |selector|
    sel = selector.to_s
    next if sel =~ /@|:/
    sel = 'body' if sel == '*' or sel == 'html'
    @document.css(sel).each do |elem|
      base = CSSPool.CSS("* {#{elem['style']}}").rule_sets.first.declarations
      elem['style'] = CSSPool::CSS.update_declarations(base, selector.declarations).join
    end
  end

  original_styles.each_pair do |elem, style|
    base = CSSPool.CSS("* {#{elem['style']}}").rule_sets.first.declarations
    orig = CSSPool.CSS("* {#{style}}").rule_sets.first.declarations
    elem['style'] = CSSPool::CSS.update_declarations(base, orig).join
  end

  @document
end