motion/http.rb in bubble-wrap-0.4.0 vs motion/http.rb in bubble-wrap-1.0.0.pre

- old
+ new

@@ -19,44 +19,44 @@ # BubbleWrap::HTTP.get("https://api.github.com/users/mattetti", {credentials: {username: 'matt', password: 'aimonetti'}}) do |response| # p response.body.to_str # prints the response's body # end # def self.get(url, options={}, &block) - delegator = block_given? ? block : options.delete(:action) - HTTP::Query.new( url, :get, options.merge({:action => delegator}) ) + create_query url, :get, options, block end # Make a POST request def self.post(url, options={}, &block) - delegator = block_given? ? block : options.delete(:action) - HTTP::Query.new( url, :post, options.merge({:action => delegator}) ) + create_query url, :post, options, block end # Make a PUT request def self.put(url, options={}, &block) - delegator = block_given? ? block : options.delete(:action) - HTTP::Query.new( url, :put, options.merge({:action => delegator}) ) + create_query url, :put, options, block end # Make a DELETE request def self.delete(url, options={}, &block) - delegator = block_given? ? block : options.delete(:action) - HTTP::Query.new( url, :delete, options.merge({:action => delegator}) ) + create_query url, :delete, options, block end # Make a HEAD request def self.head(url, options={}, &block) - delegator = block_given? ? block : options.delete(:action) - HTTP::Query.new( url, :head, options.merge({:action => delegator}) ) + create_query url, :head, options, block end # Make a PATCH request def self.patch(url, options={}, &block) - delegator = block_given? ? block : options.delete(:action) - HTTP::Query.new( url, :patch, options.merge({:action => delegator}) ) + create_query url, :patch, options, block end + private + def self.create_query(url, method, options, passed_block) + options[:action] = passed_block if passed_block + HTTP::Query.new( url, method, options ) + end + # Response class wrapping the results of a Query's response class Response attr_reader :body attr_reader :headers attr_accessor :status_code, :error_message @@ -111,54 +111,56 @@ @delegator = options.delete(:action) || self @payload = options.delete(:payload) @credentials = options.delete(:credentials) || {} @credentials = {:username => '', :password => ''}.merge(@credentials) @timeout = options.delete(:timeout) || 30.0 - headers = options.delete(:headers) - if headers - @headers = {} - headers.each{|k,v| @headers[k] = v.gsub("\n", '\\n') } # escaping LFs - end - @cachePolicy = options.delete(:cache_policy) || NSURLRequestUseProtocolCachePolicy + @headers = escape_line_feeds(options.delete :headers) + @cache_policy = options.delete(:cache_policy) || NSURLRequestUseProtocolCachePolicy @options = options @response = HTTP::Response.new initiate_request(url) connection.start UIApplication.sharedApplication.networkActivityIndicatorVisible = true connection end - def generate_get_params(payload, prefix=nil) + def generate_params(payload, prefix=nil) list = [] payload.each do |k,v| if v.is_a?(Hash) new_prefix = prefix ? "#{prefix}[#{k.to_s}]" : k.to_s - param = generate_get_params(v, new_prefix) + param = generate_params(v, new_prefix) + list << param + elsif v.is_a?(Array) + v.each do |val| + param = prefix ? "#{prefix}[#{k}][]=#{val}" : "#{k}[]=#{val}" + list << param + end else param = prefix ? "#{prefix}[#{k}]=#{v}" : "#{k}=#{v}" + list << param end - list << param end return list.flatten end def initiate_request(url_string) # http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/nsrunloop_Class/Reference/Reference.html#//apple_ref/doc/constant_group/Run_Loop_Modes # NSConnectionReplyMode unless @payload.nil? if @payload.is_a?(Hash) - params = generate_get_params(@payload) + params = generate_params(@payload) @payload = params.join("&") end url_string = "#{url_string}?#{@payload}" if @method == "GET" end - - p "BubbleWrap::HTTP building a NSRequest for #{url_string}" if SETTINGS[:debug] + #this method needs a refactor when the specs are done. (especially this utf8 escaping part) + log "BubbleWrap::HTTP building a NSRequest for #{url_string}" @url = NSURL.URLWithString(url_string.stringByAddingPercentEscapesUsingEncoding NSUTF8StringEncoding) @request = NSMutableURLRequest.requestWithURL(@url, - cachePolicy:@cachePolicy, + cachePolicy:@cache_policy, timeoutInterval:@timeout) @request.setHTTPMethod @method @request.setAllHTTPHeaderFields(@headers) if @headers # @payload needs to be converted to data @@ -166,15 +168,12 @@ @payload = @payload.to_s.dataUsingEncoding(NSUTF8StringEncoding) @request.setHTTPBody @payload end # NSHTTPCookieStorage.sharedHTTPCookieStorage - @connection = create_connection(request, self) - @request.instance_variable_set("@done_loading", false) - def @request.done_loading; @done_loading; end - def @request.done_loading!; @done_loading = true; end + patch_nsurl_request end def connection(connection, didReceiveResponse:response) @status_code = response.statusCode @response_headers = response.allHeaderFields @@ -186,11 +185,11 @@ @received_data ||= NSMutableData.new @received_data.appendData(received_data) end def connection(connection, willSendRequest:request, redirectResponse:redirect_response) - p "HTTP redirected #{request.description}" if SETTINGS[:debug] + log "HTTP redirected #{request.description}" new_request = request.mutableCopy # new_request.setValue(@credentials.inspect, forHTTPHeaderField:'Authorization') # disabled while we figure this one out new_request.setAllHTTPHeaderFields(@headers) if @headers @connection.cancel @connection = create_connection(new_request, self) @@ -198,11 +197,11 @@ end def connection(connection, didFailWithError: error) UIApplication.sharedApplication.networkActivityIndicatorVisible = false @request.done_loading! - NSLog"HTTP Connection failed #{error.localizedDescription}" if SETTINGS[:debug] + log "HTTP Connection failed #{error.localizedDescription}" @response.error_message = error.localizedDescription call_delegator_with_response end @@ -223,16 +222,38 @@ # by default we are keeping the credential for the entire session # Eventually, it would be good to let the user pick one of the 3 possible credential persistence options: # NSURLCredentialPersistenceNone, # NSURLCredentialPersistenceForSession, # NSURLCredentialPersistencePermanent - p "auth challenged, answered with credentials: #{credentials.inspect}" if SETTINGS[:debug] + log "auth challenged, answered with credentials: #{credentials.inspect}" new_credential = NSURLCredential.credentialWithUser(credentials[:username], password:credentials[:password], persistence:NSURLCredentialPersistenceForSession) challenge.sender.useCredential(new_credential, forAuthenticationChallenge:challenge) else challenge.sender.cancelAuthenticationChallenge(challenge) - p 'Auth Failed :(' + log 'Auth Failed :(' end + end + + + private + + def log(message) + NSLog message if SETTINGS[:debug] + end + + def escape_line_feeds(hash) + return nil if hash.nil? + escaped_hash = {} + + hash.each{|k,v| escaped_hash[k] = v.gsub("\n", '\\n') } + escaped_hash + end + + def patch_nsurl_request + @request.instance_variable_set("@done_loading", false) + + def @request.done_loading; @done_loading; end + def @request.done_loading!; @done_loading = true; end end def call_delegator_with_response if @delegator.respond_to?(:call) @delegator.call( @response, self )