Class: HeySpread::HTTP

Inherits:
Object
  • Object
show all
Defined in:
lib/heyspread.rb

Overview

:nodoc:

Class Method Summary collapse

Class Method Details

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

:nodoc:



512
513
514
515
516
517
518
# File 'lib/heyspread.rb', line 512

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

.parse(str) ⇒ Object



464
465
466
# File 'lib/heyspread.rb', line 464

def parse(str) 
  Hpricot.XML(str)
end

.query_to_multipart(boundary, attributes = {}) ⇒ Object

:nodoc:



495
496
497
498
499
500
501
502
503
504
# File 'lib/heyspread.rb', line 495

def query_to_multipart(boundary, attributes={}) #:nodoc:
  file = attributes.delete(:file)
  params = [file_to_multipart("file", File.basename(file), 
    "application/octet-stream", File.read(file))]
    
  attributes.each_pair{|k,v| params << text_to_multipart(k.to_s, v.to_s)}
  params.map do |p| 
    '--' + boundary + "\r\n" + p
  end.join('') + "--" + boundary + "--\r\n"
end

.query_to_string(query) ⇒ Object



520
521
522
523
524
525
526
527
528
529
# File 'lib/heyspread.rb', line 520

def query_to_string(query)
  str = ""
  query.each do |key, value|
    str << (str.empty? ? "" : "&")
    if ! value.to_s.empty?
      str << "#{key}=#{CGI::escape(value.to_s)}"
    end
  end
  str
end

.request(options = {}) ⇒ Object



468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
# File 'lib/heyspread.rb', line 468

def request(options={})
  uri = URI.parse(HeySpread::URL)        
  options[:query].merge!(:api_key => HeySpread::Account.api_key)   
  options[:path] = uri.path + options[:path]
  
  http = Net::HTTP.new(uri.host, uri.port)
  if options[:query][:file].nil?
    res = http.send_request(options[:method].to_s.upcase, options[:path], 
      query_to_string(options[:query]))
  else
					boundary = rand(9).to_s * 36					
    res = http.send_request(options[:method].to_s.upcase, options[:path], 
      query_to_multipart(boundary, options[:query]),
      "Content-Type" => "multipart/form-data; boundary=" + boundary
    )
  end
    
  body = parse(res.body || "")

  unless res.code =~ /^[2|3]/
    error = (body/"errors/error").map{|e| e.inner_html}.join(", ") rescue ""
    raise(HTTPError, "#{res.message}#{'. Reason: ' + error}")
  end
  
  body    
end

.text_to_multipart(key, value) ⇒ Object

:nodoc:



506
507
508
509
510
# File 'lib/heyspread.rb', line 506

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