We don’t allow questions seeking recommendation开发者_运维百科s for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this questionI'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"}]
You have a few options, such as...
- Ruby CSS Parser.
- TamTam
- CSSPool
精彩评论