Class: InlineStyles::Page
- Inherits:
-
Object
- Object
- InlineStyles::Page
- Defined in:
- lib/inline_styles.rb
Instance Attribute Summary collapse
-
#html ⇒ Object
Returns the value of attribute html.
Instance Method Summary collapse
- #apply(css) ⇒ Object
-
#initialize(html) ⇒ Page
constructor
A new instance of Page.
Constructor Details
#initialize(html) ⇒ Page
Returns a new instance of Page.
6 7 8 |
# File 'lib/inline_styles.rb', line 6 def initialize(html) @html = html end |
Instance Attribute Details
#html ⇒ Object
Returns the value of attribute html.
4 5 6 |
# File 'lib/inline_styles.rb', line 4 def html @html end |
Instance Method Details
#apply(css) ⇒ Object
10 11 12 13 14 15 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 42 43 44 45 46 47 |
# File 'lib/inline_styles.rb', line 10 def apply(css) require_dependencies parser = CssParser::Parser.new parser.add_block! css tree = Hpricot(html) 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.each do |selector, declarations, spec| # Find each element matching the given slector (tree/selector).each do |element| # 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 |