I'm looking for a CSS parser, similar to this one Looking for a CSS Parser in java , but in Ruby.
Input: an element of a HTML document.
Output: all styles associated to that specific element.
I've googled for it, and I've also searched here at Stackoverflow, but all I could find was this Java parser.
I also needed a CSS parser but none listed in the accepted answer could parse CSS3.
I ended using Sass with a little extension:
require 'sass'
class Sass::Tree::Visitors::ToArray < Sass::Tree::Visitors::Base
protected
def initialize
@array = []
end
def visit(node, parent = false)
if node_name(parent) == "root"
@media = "all"
end
method = "visit_#{node_name(node)}"
if self.respond_to?(method, true)
self.send(method, node)
else
visit_children(node)
end
@array
end
def visit_children(parent)
parent.children.map {|c| visit(c, parent)}
end
def visit_root(node)
visit_children(node)
end
def visit_media(node)
@media = node.query.join('')
visit_children(node)
end
def visit_rule(node)
@selector = node.rule[0]
visit_children(node)
end
def visit_prop(node)
return unless node.value
@array << {
media: @media,
selector: @selector,
property: node.name[0],
value: node.value.to_sass
}
end
end
class Sass::Tree::Node
def to_a
Sass::Tree::Visitors::ToArray.visit(self)
end
end
With the code above,
Sass::Engine.new("body {color: #f00}, p {font-size: 20px}", :syntax => :scss).to_tree.to_a
will result in
> [{:media=>:all, :selector=>"body", :property=>"color", :value=>"#f00"}, {:media=>:all, :selector=>"p", :property=>"font-size", :value=>"20px"}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With