Class: AssertValidContent::W3C::CSS

Inherits:
Validator
  • Object
show all
Defined in:
lib/assert_valid_content/w3c-net.rb

Overview

Validates via the W3C CSS validator service (taken from assert-valid-asset).

Constant Summary collapse

SrvHost =
ENV['CSS_VALIDATOR_HOST'] || 'jigsaw.w3.org'
SrvPath =
ENV['CSS_VALIDATOR_PATH'] || '/css-validator/validator'
TempDir =
File.join AssertValidContent::TempDir, 'w3c-net'

Instance Attribute Summary

Attributes inherited from Validator

#errors

Instance Method Summary collapse

Methods inherited from Validator

#initialize, #to_s, validates

Constructor Details

This class inherits a constructor from AssertValidContent::Validator

Instance Method Details

#file_to_multipart(key, filename, mime_type, content) ⇒ Object

:nodoc:



58
59
60
61
# File 'lib/assert_valid_content/w3c-net.rb', line 58

def file_to_multipart(key,filename,mime_type,content)  #:nodoc:
  "Content-Disposition: form-data; name=\"#{CGI::escape(key)}\"; filename=\"#{filename}\"\r\n" +
    "Content-Transfer-Encoding: binary\r\nContent-Type: #{mime_type}\r\n\r\n#{content}\r\n"
end

#httpObject

:nodoc:



63
64
65
66
67
68
69
# File 'lib/assert_valid_content/w3c-net.rb', line 63

def http  #:nodoc:
  if Module.constants.include?('ApplicationConfig') and ApplicationConfig.respond_to?(:proxy_config)
    Net::HTTP::Proxy ApplicationConfig.proxy_config['host'], ApplicationConfig.proxy_config['port']
  else
    Net::HTTP
  end
end

#text_to_multipart(key, value) ⇒ Object

:nodoc:



54
55
56
# File 'lib/assert_valid_content/w3c-net.rb', line 54

def text_to_multipart(key,value)  #:nodoc:
  "Content-Disposition: form-data; name=\"#{CGI::escape(key)}\"\r\n\r\n#{value}\r\n"
end

#validate(content) ⇒ Object

:nodoc:



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/assert_valid_content/w3c-net.rb', line 21

def validate( content )  #:nodoc:
  FileUtils.mkdir_p TempDir

  md5 = MD5.md5( content ).to_s
  resp_path = File.join TempDir, md5

  begin
    resp = File.read resp_path

  rescue
    params = [
      file_to_multipart( 'file', 'file.css', 'text/css', content ),
      text_to_multipart( 'warning', '1' ),
      text_to_multipart( 'profile', 'css2' ),
      text_to_multipart( 'usermedium', 'all' ),
    ]
    boundary = '-----------------------------24464570528145'
    query = params.collect { |p| "--#{boundary}\r\n#{p}" }.join + "--#{boundary}--\r\n"
    type = "multipart/form-data; boundary=#{boundary}"

    resp = http.start(SrvHost).post2( SrvPath, query, 'Content-type' => type ).body
    File.open( resp_path, 'w+' ) { |f|  f.write resp }
  end

  begin
    root = REXML::Document.new( resp ).root
    REXML::XPath.each( root, "//x:tr[@class='error']", { "x"=>"http://www.w3.org/1999/xhtml" } )  do |el|
      @errors << "Invalid CSS: line" + el.to_s.gsub(/<[^>]+>/,' ').gsub(/\n/,' ').gsub(/\s+/, ' ')
    end
  rescue REXML::ParseException
  end
end