Module: Validator

Defined in:
lib/validator.nu.rb

Defined Under Namespace

Classes: RemoteException

Constant Summary collapse

CONTENT_ENCODING =
"UTF-8"
CONTENT_TYPE =
"text/html; charset=utf-8"
HOST =
"validator.nu"
GZIP =
false
PORT =
80

Class Method Summary collapse

Class Method Details

.get(url, options) ⇒ Object

TODO - some implementation notes. http.set_debug_output STDERR http.use_ssl = true if SSL headers = method.to_s == ‘errors’ ? { ‘Content-Type’ => ‘application/x-gzip’, ‘Accept’ => ‘application/x-gzip’ } : {} compressed_data = CGI::escape(Zlib::Deflate.deflate(data, Zlib::BEST_SPEED)) STDERR.puts uri



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/validator.nu.rb', line 62

def get(url, options)
  begin
    host = options[:host] || HOST
    port = options[:port] || PORT
    http = Net::HTTP.new(host, port)
    uri = "/?&doc=#{CGI::escape(url.to_s)}&out=json"

    response = http.start do |http|
      http.get(uri)
    end
    
    if response.kind_of? Net::HTTPSuccess
      return response.body
    else
      STDERR.puts response.body.inspect
      raise RemoteException.new("#{response.code}: #{response.message}")
    end

  rescue Exception => e
    STDERR.puts "Error contacting validator.nu: #{e}"
    STDERR.puts e.backtrace.join("\n"), 'debug'
    raise e
  end
end

.nu(uri_or_document, options = {}) ⇒ Object



48
49
50
51
52
53
54
# File 'lib/validator.nu.rb', line 48

def nu(uri_or_document, options={})
  if uri_or_document.kind_of?(URI::HTTP)
    get(uri_or_document, options)          
  else
    post(uri_or_document, options)          
  end
end

.post(document, options) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/validator.nu.rb', line 87

def post(document, options)
  begin
    host = options[:host] || HOST
    port = options[:port] || PORT
    content_type = options[:content_type] || CONTENT_TYPE
    content_encoding = options[:content_encoding] || CONTENT_ENCODING
    gzip = options[:gzip] || GZIP

    if gzip
      content_encoding = 'gzip'
      output = StringIO.new
      gz = Zlib::GzipWriter.new(output)
      gz.write(document)
      gz.close
      document = output.string
    end

    http = Net::HTTP.new(host, port)
    uri = "/?out=json"
    headers = { 'Content-Type' => content_type, 'Content-Encoding' => content_encoding }

    response = http.start do |http|
      http.post(uri, document, headers) 
    end
    
    if response.kind_of? Net::HTTPSuccess
      return response.body
    else
      STDERR.puts response.body.inspect
      raise RemoteException.new("#{response.code}: #{response.message}")
    end

  rescue Exception => e
    STDERR.puts "Error contacting validator.nu: #{e}"
    STDERR.puts e.backtrace.join("\n"), 'debug'
    raise e
  end
end