Skip to content

Instantly share code, notes, and snippets.

@tpitale
Created January 6, 2011 16:08
Show Gist options
  • Save tpitale/768079 to your computer and use it in GitHub Desktop.
Save tpitale/768079 to your computer and use it in GitHub Desktop.
Async MacRuby HTTP
module Kermit
class Request
def initialize(url, success, failure=nil)
@request = NSURLRequest.requestWithURL(NSURL.URLWithString(url))
@success = success
@failure = failure
# @parser = Yajl::Parser.new(:symbolize_keys => true)
end
def connection
@connection ||= NSURLConnection.alloc.initWithRequest(@request, delegate:self)
end
def perform_request
self.connection.start
end
def connection(connection, didFailWithError:error)
# puts error.code.inspect
# puts error.domain.inspect
# puts error.userInfo.inspect
end
def success?
@status_code == 200
end
def connection(connection, didReceiveResponse:response)
@status_code = response.statusCode
@response_body = "" if success?
end
def connection(connection, didReceiveData:data)
if success?
(0...length).each {|i| @response_body << data.bytes[i].chr}
end
end
def connectionDidFinishLoading(connection)
if success?
@success.call(JSON.parse(@response_body))
else
@failure.call(@status_code) if @failure
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment