Rails CSS uploader/validator


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  1. #!/usr/bin/env ruby
  2.  
  3. curl = `which curl 2>/dev/null`.chomp
  4. validator = 'http://jigsaw.w3.org/css-validator/validator'
  5.  
  6. # All warnings, CSS2, all mediums
  7. options = 'warning=2&profile=css2&usermedium=all'
  8.  
  9. base = File.expand_path("#{File.dirname(__FILE__)}/../../public/stylesheets")
  10.  
  11. # Got curl?
  12. raise "Curl not found" if curl.empty?
  13.  
  14. # Get path to stylesheets
  15. if ARGV.size > 0
  16. base = ARGV.shift
  17. end
  18.  
  19. # All css files or just one?
  20. glob = base =~ /css$/ ? base : "#{base}/*.css"
  21.  
  22. # Do files
  23. Dir.glob(glob) do |file|
  24.  
  25. next unless File.exists?( file )
  26.  
  27. errors, warnings = [ ], [ ]
  28.  
  29. # Send the css file to the validator
  30. results = `#{curl} -s -F "file=@#{file}" -F "#{options}" #{validator}`
  31.  
  32. # Validator couldn't find the file
  33. #
  34. # OR the file didn't have _any_ valid css content before
  35. # the errors <- little gotcha
  36. #
  37. results.grep(/No style sheet found/) do |line|
  38. STDERR << "#{$&}\n"
  39. exit
  40. end
  41.  
  42. # Add new lines to <li></li> tags so grep can find them easier
  43. results.gsub!(/\n/,'').gsub!(/<li>/,"\n<li>").gsub!(/<\/li>/,"</li>\n")
  44.  
  45. results.grep(/<li>.*<\/li>/) do |line|
  46.  
  47. # collect errors
  48. line.grep(/<span class='error'>/) do |error|
  49. errors << error.gsub!(/(<p>|<\/p>)/,"\n").gsub!(/<(.|\n)*?>/, '')
  50. end
  51.  
  52. end
  53.  
  54. # collect warnings
  55. results.grep(/<span class='warning'>/) do |line|
  56. warnings << line.gsub!(/<(.|\n)*?>/, '')
  57. end
  58.  
  59. # Dump information to STDERR
  60. STDERR << "CSS File #{file}:\n\n"
  61.  
  62. { 'Errors' => errors, 'Warnings' => warnings }.each do |k,v|
  63.  
  64. if v.empty?
  65. STDERR << "No #{k.downcase} found\n---------------\n\n"
  66. else
  67. STDERR << "#{k} found:\n-------------\n\n"
  68. v.each {|line| STDERR << line}
  69. end
  70.  
  71. end
  72.  
  73. end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.