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:



519
520
521
522
523
524
525
# File 'lib/heyspread.rb', line 519

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



471
472
473
# File 'lib/heyspread.rb', line 471

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

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

:nodoc:



502
503
504
505
506
507
508
509
510
511
# File 'lib/heyspread.rb', line 502

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



527
528
529
530
531
532
533
534
535
536
# File 'lib/heyspread.rb', line 527

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



475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# File 'lib/heyspread.rb', line 475

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:



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

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