Skip to content

Instantly share code, notes, and snippets.

@drernie
Created August 22, 2008 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drernie/6863 to your computer and use it in GitHub Desktop.
Save drernie/6863 to your computer and use it in GitHub Desktop.
Parse CSS 3 Media Queries
#!/usr/bin/env ruby
#
# mqparse - Media Query parser
# Copyright 2008 Apple, Inc. All Rights Reserved.
# http://gist.github.com/6863
#
# cf. http://www.w3.org/TR/css3-mediaqueries
require 'pp'
TOKEN = '([\w\-]+)' # letters, numbers, or "-"
# Match against strings of form: key, (key), or (key: value)
KEYVALUE = Regexp.new("\\(#{TOKEN}(: #{TOKEN})?\\)", Regexp::IGNORECASE)
COMPARATOR = Regexp.new("(min|max)-#{TOKEN}", Regexp::IGNORECASE)
COMPARE = {"min" => ">=", "max" => "<="}
def mq_parse(mq_string)
mq_string.split(",").collect do |query|
query.split(" and ").collect do |expr|
matched,key,_,value = *KEYVALUE.match(expr)
next ["media-type", "==", expr] if not matched
next [key, "!=", "0"] if value.nil?
comparison, side, root = *COMPARATOR.match(key)
next [key, "==", value] if not comparison
[root, COMPARE[side], value]
end # expr
end # query
end # mq_parse
parse_string = "screen "+
"and (min-device-height: 640) "+
"and (width: 720) "+
"and (device-type: ipod) "+
"and (color: rgb),"+
" (color)"
puts "\n\tParsing:\n#{parse_string}"
qs = mq_parse(parse_string)
qs.each_index do |i|
puts "\n\tQuery #{i}:"
pp *qs[i]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment