Is it possible to parse a stylesheet with Nokogiri?

Posted by wbharding on Stack Overflow See other posts from Stack Overflow or by wbharding
Published on 2010-05-30T21:45:23Z Indexed on 2010/05/30 21:52 UTC
Read the original article Hit count: 290

Filed under:
|
|
|

I've spent my requisite two hours Googling this, and I can not find any good answers, so let's see if humans can beat Google computers.

I want to parse a stylesheet in Ruby so that I can apply those styles to elements in my document (to make the styles inlined). So, I want to take something like

<style>
.mystyle {
  color:white;
}
</style>

And be able to extract it into a Nokogiri object of some sort.

The Nokogiri class "CSS::Parser" (http://nokogiri.rubyforge.org/nokogiri/Nokogiri/CSS/Parser.html) certainly has a promising name, but I can't find any documentation on what it is or how it works, so I have no idea if it can do what I'm after here.

My end goal is to be able to write code something like:

a_web_page = Nokogiri::HTML(html_page_as_string)
parsed_styles = Nokogiri::CSS.parse(html_page_as_string)
parsed_styles.each do |style| 
  existing_inlined_style = a_web_page.css(style.declaration) || ''
  a_web_page.css(style.declaration)['css'] = existing_inlined_style + style.definition
end

Which would extract styles from a stylesheet and add them all as inlined styles to my document.

© Stack Overflow or respective owner

Related posts about css

Related posts about stylesheet