Class: PleaseValidate::Validator
- Inherits:
-
Object
- Object
- PleaseValidate::Validator
- Defined in:
- lib/please_validate/validator.rb
Class Method Summary collapse
-
.file(file) ⇒ Object
Read requested file’s contents and send to the w3c validator api then call the parse_response method to sort the response out.
-
.file_valid?(file) ⇒ Boolean
Takes a file path and checks to see if it’s mime type is OK.
-
.files(files) ⇒ Object
Takes an array of files and validates them all.
-
.parse_response(filename, response) ⇒ Object
Takes an XML response from the file method’s call to the w3c and parses it into a nice little hash.
Class Method Details
.file(file) ⇒ Object
Read requested file’s contents and send to the w3c validator api then call the parse_response method to sort the response out.
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/please_validate/validator.rb', line 7 def file(file) begin raise "please specify a file to validate" unless file raise "#{file} doesn't exist" unless File.exist? file raise "#{file} must have a content type of text/html" unless file_valid? file response = File.open(file, 'r') do |f| Net::HTTP.start('validator.w3.org').post( '/check', "fragment=#{CGI.escape(f.read)}&output=xml", {'Content-Type' => 'application/x-www-form-urlencoded'} ) end parse_response file, response end end |
.file_valid?(file) ⇒ Boolean
Takes a file path and checks to see if it’s mime type is OK. Currently using the first mime type returned by the mime-types gem.
62 63 64 65 |
# File 'lib/please_validate/validator.rb', line 62 def file_valid?(file) mime = MIME::Types.type_for(file).first !mime.nil? && ACCEPTED_MIMES.include?(mime.content_type) end |
.files(files) ⇒ Object
Takes an array of files and validates them all
24 25 26 27 28 29 30 31 32 |
# File 'lib/please_validate/validator.rb', line 24 def files(files) files.uniq.collect do |file| begin self.file(file) rescue Exception => e "Validation failed: #{e}" end end end |
.parse_response(filename, response) ⇒ Object
Takes an XML response from the file method’s call to the w3c and parses it into a nice little hash
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/please_validate/validator.rb', line 35 def parse_response(filename, response) # Use Nokogiri to parse the xml response_data = Nokogiri::XML.parse(response.body) # Begin building the return hash result = { :file => filename, :status => response['x-w3c-validator-status'].downcase.to_sym, :error_count => response['x-w3c-validator-errors'].to_i, :errors => Array.new } # Get meta elements like encoding and doctype response_data.css('result > meta *').each do || next unless %w{encoding doctype}.include? .name result[.name.to_sym] = .content end # Get errors response_data.css('result messages msg').each do |error| result[:errors] << { :message => error.content, :line => error['line'].to_i, :col => error['col'].to_i } end result end |