Finding CSS Parser in Ruby

I am looking for a CSS parser similar to this CSS parser search in java but in Ruby.

Input: HTML document element.

Exit: all styles associated with this particular element.

I searched this for a search, and I also searched here on Stackoverflow, but all I could find was this Java parser.

+5
source share
2 answers

You have several options, for example ...

+4
source

I also need a CSS parser, but none of the ones in the accepted answer could parse CSS3.

I ended up 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

Sass::Engine.new("body {color: #f00}, p {font-size: 20px}", :syntax => :scss).to_tree.to_a

> [{:media=>:all, :selector=>"body", :property=>"color", :value=>"#f00"}, {:media=>:all, :selector=>"p", :property=>"font-size", :value=>"20px"}]
+5

All Articles