Tuesday, August 17, 2010

how to parse css (css_parser)

How to parse css and get css file elements in Ruby?
You can parse both local css file as well as remote css file also by Using Css_parser gem.

For install simple do "gem install css_parser." or use http://github.com/alexdunae/css_parser for github.

Below is the example of use Remote Css :
require 'rubygems'
require 'css_parser'
include CssParser

parser = CssParser::Parser.new
parser.load_uri!('http://example.com/styles/style.css')

# load a remote file, setting the base_uri and media_types
parser.load_uri!('../style.css', 'http://example.com/styles/inc/', [:screen, :handheld])

# load a local file, setting the base_dir and media_types
parser.load_file!('print.css', '~/styles/', :print)

# lookup a rule by a selector
parser.find('#content')
#=> 'font-size: 13px; line-height: 1.2;'

# lookup a rule by a selector and media type
parser.find('#content', [:screen, :handheld])

# iterate through selectors by media type
parser.each_selector(:screen) do |selector, declarations, specificity|
...
end

# add a block of CSS
css = <<-EOT
body { margin: 0 1em; }
EOT

parser.add_block!(css)

# output all CSS rules in a single stylesheet
parser.to_s
=> #content { font-size: 13px; line-height: 1.2; }
body { margin: 0 1em; }




How to parse local Css??

For that you have to do some change in css_parser gem's file "lib/css_parser/parser.rb"

and add following method into it after "load_uri! method.

# Load a local CSS file.
def load_file!(file_name, base_dir = nil, media_types = :all)
file_name = File.expand_path(file_name, base_dir)
return unless File.readable?(file_name)

src = IO.read(file_name)
base_dir = File.dirname(file_name)

add_block!(src, {:media_types => media_types, :base_dir => base_dir})
end

For more changes and details you have to check :

http://github.com/zapnap/css_parser/blob/master/lib/css_parser/parser.rb


Example For Local css parse:
require 'rubygems'
require 'css_parser'
include CssParser

parser = CssParser::Parser.new
parser.load_file!("test.css")
@info = parser.find_by_selector("body")