Class: TwitPic
- Inherits:
-
Object
- Object
- TwitPic
- Defined in:
- lib/twitpic.rb
Defined Under Namespace
Classes: APIError
Constant Summary collapse
- VERSION =
'0.3.1'
Instance Method Summary collapse
- #create_body(parts, file_path, boundary) ⇒ Object
-
#initialize(username, password) ⇒ TwitPic
constructor
A new instance of TwitPic.
- #parse_response(xml) ⇒ Object
- #post(url, body, boundary) ⇒ Object
- #upload(file_path, message = nil, boundary = "----------------------------TwitPic#{rand(1000000000000)}") ⇒ Object
Constructor Details
#initialize(username, password) ⇒ TwitPic
Returns a new instance of TwitPic.
11 12 13 14 |
# File 'lib/twitpic.rb', line 11 def initialize(username, password) @username = username @password = password end |
Instance Method Details
#create_body(parts, file_path, boundary) ⇒ Object
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/twitpic.rb', line 60 def create_body(parts, file_path, boundary) parts[:media] = open(file_path, 'rb').read body = '' [:media, :username, :password, :message].each do |key| value = parts[key] next unless value body << "--#{boundary}\r\n" if key == :media body << "Content-Disposition: form-data; name=\"#{key}\"; filename=\"#{File.basename(file_path)}\"\r\n" body << "Content-Type: #{MIME::Types.type_for(file_path).first.content_type}\r\n" else body << "Content-Disposition: form-data; name=\"#{key}\"\r\n" end body << "\r\n" body << "#{value}\r\n" end body << "--#{boundary}--\r\n" end |
#parse_response(xml) ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/twitpic.rb', line 46 def parse_response(xml) doc = REXML::Document.new(xml) error_element = REXML::XPath.match(doc, "/rsp/err").first if error_element raise APIError, error_element.attribute('code').value + ': ' + error_element.attribute('code').value else result = {} [:statusid, :userid, :mediaid, :mediaurl].each do |key| result[key] = REXML::XPath.match(doc, "/rsp/#{key}").first.text rescue nil end result end end |
#post(url, body, boundary) ⇒ Object
35 36 37 38 39 40 41 42 43 44 |
# File 'lib/twitpic.rb', line 35 def post(url, body, boundary) uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) xml = http.start do |http| headers = {"Content-Type" => "multipart/form-data; boundary=" + boundary} response = http.post(uri.path, body, headers) response.body end parse_response(xml) end |
#upload(file_path, message = nil, boundary = "----------------------------TwitPic#{rand(1000000000000)}") ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/twitpic.rb', line 16 def upload(file_path, = nil, boundary = "----------------------------TwitPic#{rand(1000000000000)}") parts = { :username => @username, :password => @password } parts[:message] = if && !.empty? body = create_body(parts, file_path, boundary) url = if parts[:message] 'http://twitpic.com/api/uploadAndPost' else 'http://twitpic.com/api/upload' end post(url, body, boundary) end |