Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Fetching latest commit…

Octocat-spinner-32-eaf2f5

Cannot retrieve the latest commit at this time

Octocat-spinner-32 lib
Octocat-spinner-32 test
Octocat-spinner-32 .gitignore
Octocat-spinner-32 .travis.yml
Octocat-spinner-32 CHANGELOG
Octocat-spinner-32 Gemfile
Octocat-spinner-32 Gemfile.lock
Octocat-spinner-32 LICENSE
Octocat-spinner-32 README.rdoc
Octocat-spinner-32 css_parser.gemspec
Octocat-spinner-32 rakefile.rb
README.rdoc

Ruby CSS Parser

Load, parse and cascade CSS rule sets in Ruby.

Setup

Install the gem.

gem install css_parser

Done.

An example

require 'css_parser'
include CssParser

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

parser = CssParser::Parser.new
parser.load_uri!('file://home/user/styles/style.css')

# load a remote file, setting the base_uri and media_types
parser.load_uri!('../style.css', {:base_uri => 'http://example.com/styles/inc/', :media_types => [: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_by_selector('#content')
#=> 'font-size: 13px; line-height: 1.2;'

# lookup a rule by a selector and media type
parser.find_by_selector('#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; }

Testing

You can run the suite of unit tests using rake test.

The download/import tests use WEBrick. The tests set up a temporary server on port 12000 and pull down files from the test/fixtures/ directory.

Tested with Ruby 1.8.7, Ruby 1.9.2, Ruby 1.9.3-preview1, REE 1.8.7 and JRuby 1.6.4.

Credits and code

By Alex Dunae (dunae.ca, e-mail 'code' at the same domain), 2007-11.

Project homepage: github.com/alexdunae/css_parser

Thanks to all the wonderful contributors for their updates.

Made on Vancouver Island.

Something went wrong with that request. Please try again.