Created
August 22, 2008 22:21
-
-
Save drernie/6863 to your computer and use it in GitHub Desktop.
Parse CSS 3 Media Queries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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