Load, parse and cascade CSS rule sets in Ruby.
gem install css_parserrequire'css_parser'includeCssParserparser=CssParser::Parser.newparser.load_uri!('http://example.com/styles/style.css')parser=CssParser::Parser.newparser.load_uri!('file://home/user/styles/style.css')# load a remote file, setting the base_uri and media_typesparser.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_typesparser.load_file!('print.css','~/styles/',:print)# load a stringparser=CssParser::Parser.newparser.load_string!'a { color: hotpink; }'# lookup a rule by a selectorparser.find_by_selector('#content')#=> 'font-size: 13px; line-height: 1.2;'# lookup a rule by a selector and media typeparser.find_by_selector('#content',[:screen,:handheld])# iterate through selectors by media typeparser.each_selector(:screen)do |selector,declarations,specificity|
...
end# add a block of CSScss=<<-EOT body { margin: 0 1em; }EOTparser.add_block!(css)# output all CSS rules in a single stylesheetparser.to_s=>#content { font-size: 13px; line-height: 1.2; }body{margin: 01em;}# capturing byte offsets within a fileparser.load_uri!('../style.css',{base_uri: 'http://example.com/styles/inc/',capture_offsets: true)content_rule=parser.find_rule_sets(['#content']).firstcontent_rule.filename#=> 'http://example.com/styles/styles.css'content_rule.offset#=> 10703..10752# capturing byte offsets within a stringparser.load_string!('a { color: hotpink; }',{filename: 'index.html',capture_offsets: true)content_rule=parser.find_rule_sets(['a']).firstcontent_rule.filename#=> 'index.html'content_rule.offset#=> 0..21bundle
bundle exec rakeRuns on Ruby 3.0/JRuby 9.4 or above.
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.