Ruby CSS Parser
Load, parse and cascade CSS rule sets in Ruby.
Setup
gem install css_parser
Usage
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')
parser.load_uri!('../style.css', {base_uri: 'http://example.com/styles/inc/', media_types: [:screen, :handheld]})
parser.load_file!('print.css', '~/styles/', :print)
parser = CssParser::Parser.new
parser.load_string! 'a { color: hotpink; }'
parser.find_by_selector('#content')
parser.find_by_selector('#content', [:screen, :handheld])
parser.each_selector(:screen) do |selector, declarations, specificity|
...
end
css = <<-EOT
body { margin: 0 1em; }
EOT
parser.add_block!(css)
parser.to_s
=>
body { margin: 0 1em; }
parser.load_uri!('../style.css', {base_uri: 'http://example.com/styles/inc/', capture_offsets: true)
content_rule = parser.find_rule_sets(['#content']).first
content_rule.filename
content_rule.offset
parser.load_string!('a { color: hotpink; }', {filename: 'index.html', capture_offsets: true)
content_rule = parser.find_rule_sets(['a']).first
content_rule.filename
content_rule.offset
Testing
bundle
bundle exec rake
Runs on Ruby 3.0/JRuby 9.4 or above.
Credits
By Alex Dunae (dunae.ca, e-mail 'code' at the same domain), 2007-11.
License: MIT
Thanks to all the wonderful contributors for their updates.
Made on Vancouver Island.