Load, parse and cascade CSS rule sets in Ruby.
Install the gem (hosted on GemCutter).
gem sources -a http://gemcutter.org/ gem install css_parser
Done.
require 'css_parser'
include CssParser
parser = CssParser::Parser.new
parser.load_file!('http://example.com/styles/style.css')
# 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; }
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.
By Alex Dunae (dunae.ca, e-mail ‘code’ at the same domain), 2007-09.
Project homepage: github.com/alexdunae/css_parser
Thanks to Tyler Cunnion for the updates leading to 1.0.0.
Made on Vancouver Island.