Module: CSSPlop

Defined in:
lib/cssplop.rb,
lib/cssplop/version.rb

Constant Summary collapse

VERSION =
"0.1.1"

Class Method Summary collapse

Class Method Details

.apply(stylesheet, document) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/cssplop.rb', line 21

def self.apply stylesheet, document
  css_doc = if stylesheet.is_a? CSSPool::CSS::Document
    stylesheet
  else
    CSSPool.CSS stylesheet
  end

  html_doc = if document.is_a? Nokogiri::XML::Node
    document.dup # no sideeffects
  else
    Nokogiri::HTML.fragment document
  end

  self.apply! css_doc, html_doc

  if document.is_a? Nokogiri::XML::Node
    return html_doc
  else
    return html_doc.to_html
  end
end

.apply!(stylesheet, document) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/cssplop.rb', line 43

def self.apply! stylesheet, document
  elements_declarations_map = {}

  stylesheet.rule_sets.each do |rule_set|
    selectors = rule_set.selectors.map &:to_css
    elements = document.css *selectors
    elements.each do |element|
      elements_declarations_map[element] ||= []
      elements_declarations_map[element].concat rule_set.declarations
    end
  end

  elements_declarations_map.each do |element, declarations|
    element_style_doc = CSSPool.CSS "* {#{element[:style]}}"
    element_declarations = element_style_doc.rule_sets.first.declarations
    element_declarations.concat declarations.flatten

    element[:style] = element_declarations.map(&:to_css).join.strip
  end

  return document
end

.inline_styles(document) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/cssplop.rb', line 5

def self.inline_styles document
  html_doc = Nokogiri::HTML.fragment document

  # All styles that don't have sources.
  styles = html_doc.xpath 'descendant-or-self::style[not(@src)]'
  styles.each do |style|
    begin
      stylesheet = CSSPool::CSS style.text
      self.apply! stylesheet, html_doc
      style.remove
    end
  end

  return html_doc.to_html
end