Syntax for passing the content of a file to a post request using rest-client


Carlos Araya <carlos.araya@...>
 

I have the following code in the file lib/validator.rb

#!/usr/bin/env ruby -d
require 'json'
require 'rest_client'

module Ctools
class Validator
# Based on the code from
https://github.com/damian/html5_validator/blob/master/lib/html5_validator.rb

attr_reader :errors
BASE_URI = 'http://html5.validator.nu'
HEADERS = { 'Content-Type' => 'text/html; charset=utf-8',
'Content-Encoding' => 'UTF-8' }

def initialize(proxy = nil)
RestClient.proxy = proxy unless proxy.nil?
@errors = []
end

# Validate the markup of a String
def check_content(text)
response = RestClient.post "#{BASE_URI}/?out=json", text, HEADERS
@json = JSON.parse(response.body)
@errors = retrieve_errors
end

# Validate the markup of a URI
def check_uri(uri)
response = RestClient.get BASE_URI, :params => { :doc => uri,
:out => 'json' }
@json = JSON.parse(response.body)
@errors = retrieve_errors
end

def inspect
@errors.map do |err|
"- Error: #{err['message']}"
end.join("\n")
end

def valid?
@errors.length == 0
end

private

def retrieve_errors
@json['messages'].select { |mssg| mssg['type'] == 'error' }
end
end #class
end # module


The code is called from validator_test.rb as follows:


#!/usr/local/bin/ruby -d

require_relative '../lib/ctools/validator.rb'

# p $LOAD_PATH
@html = File.new('/Users/carlos/experiment/code/ctools/test/index.html').read
# p @html
check = Ctools::Validator.new
check.check_content(@html)

but I get the following output:

rivendell:ctools carlos$ bin/validate_test.rb
Using c extension for JSON.
Exception `LoadError' at <internal:lib/rubygems/custom_require>:29 -
no such file to load -- rest_client
Type multipart/x-parallel already registered as a variant of multipart/parallel.
Type text/plain already registered as a variant of text/plain.
/usr/local/lib/ruby/gems/1.9.1/gems/rest-client-1.6.7/lib/restclient/response.rb:11:
warning: method redefined; discarding old body
/usr/local/lib/ruby/gems/1.9.1/gems/rest-client-1.6.7/lib/restclient/payload.rb:47:
warning: mismatched indentations at 'end' with 'case' at 40
Exception `Errno::EAGAIN' at
/usr/local/lib/ruby/1.9.1/net/protocol.rb:135 - Resource temporarily
unavailable - read would block
Exception `Errno::EAGAIN' at
/usr/local/lib/ruby/1.9.1/net/protocol.rb:135 - Resource temporarily
unavailable - read would block

Is this a problem with rest_client or with the way I'm calling it in my code?

Carlos

Join main@rest-client.groups.io to automatically receive all group messages.