Class: InlineStyles::Page

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(html = nil) ⇒ Page

Returns a new instance of Page.



8
9
10
# File 'lib/inline_styles.rb', line 8

def initialize(html = nil)
  @html = html
end

Instance Attribute Details

#htmlObject

Returns the value of attribute html.



6
7
8
# File 'lib/inline_styles.rb', line 6

def html
  @html
end

Instance Method Details

#apply(stylesheet_content = nil) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/inline_styles.rb', line 46

def apply(stylesheet_content = nil)
  with_css(stylesheet_content) if stylesheet_content

  tree = Nokogiri::HTML(@html)

  selectors.each do |selector, declarations, spec|
    # Find each element matching the given slector
    (tree.css selector).each do |element|

      next unless element.respond_to?(:[])
      # Merge any previously-inlined style with the
      # latest (higher specificity) one
      element['style'] ||= ''
      element['style'] = CssParser.merge(
        CssParser::RuleSet.new('', element['style'], 1),
        CssParser::RuleSet.new('', declarations, 2)
      ).declarations_to_s
    end
  end

  tree.to_s
end

#selectorsObject



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

def selectors
  @selectors ||= begin
    parser = CssParser::Parser.new
    parser.add_block! @css

    stable_sorter = 0
    selectors = []

    # extracting selectors via the API rather than
    # just reaching in and grabbing @selectors
    parser.each_selector do |selector, declarations, specificity|
      selectors << [selector, declarations, specificity]
    end

    # stable-sort the selectors so that we get them sorted
    # by specificity but also keeping their rough
    # original order. This is how CSS selectors are applied
    # in a browser
    selectors.sort_by do |selector|
      [selector.last, stable_sorter += 1]
    end
  end
end

#with_css(css) ⇒ Object



12
13
14
15
# File 'lib/inline_styles.rb', line 12

def with_css(css)
  @css = css
  self
end

#with_html(html) ⇒ Object



17
18
19
20
# File 'lib/inline_styles.rb', line 17

def with_html(html)
  @html = html
  self
end