Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for a CSS parser in Ruby [closed]

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.

like image 566
JoaoHornburg Avatar asked Mar 01 '11 23:03

JoaoHornburg


1 Answers

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"}]
like image 148
sorich87 Avatar answered Oct 13 '22 11:10

sorich87