1 # Copyright 2010 Google Inc.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
18 # This class wraps a result returned by an API call.
20 def initialize(reference, request, response)
21 @reference = reference
26 attr_reader :reference
41 return @body ||= (begin
42 response_body = @response[2]
43 merged_body = (response_body.inject(StringIO.new) do |accu, chunk|
51 return @data ||= (begin
52 _, content_type = self.headers.detect do |h, v|
53 h.downcase == 'Content-Type'.downcase
55 media_type = content_type[/^([^;]*);?.*$/, 1].strip.downcase
58 when 'application/json'
59 data = JSON.parse(data)
60 # Strip data wrapper, if present
61 data = data['data'] if data.has_key?('data')
64 "Content-Type not supported for parsing: #{media_type}"
66 if @reference.api_method && @reference.api_method.response_schema
67 # Automatically parse using the schema designated for the
68 # response of this API method.
69 data = @reference.api_method.response_schema.new(data)
72 # Otherwise, return the raw unparsed value.
73 # This value must be indexable like a Hash.
88 if self.data.respond_to?(:next_page_token)
89 return self.data.next_page_token
90 elsif self.data.respond_to?(:[])
91 return self.data["nextPageToken"]
93 raise TypeError, "Data object did not respond to #next_page_token."
98 merged_parameters = Hash[self.reference.parameters].merge({
99 self.page_token_param => self.next_page_token
101 # Because References can be coerced to Hashes, we can merge them,
102 # preserving all context except the API method parameters that we're
103 # using for pagination.
104 return Google::APIClient::Reference.new(
105 Hash[self.reference].merge(:parameters => merged_parameters)
110 if self.data.respond_to?(:prev_page_token)
111 return self.data.prev_page_token
112 elsif self.data.respond_to?(:[])
113 return self.data["prevPageToken"]
115 raise TypeError, "Data object did not respond to #next_page_token."
120 merged_parameters = Hash[self.reference.parameters].merge({
121 self.page_token_param => self.prev_page_token
123 # Because References can be coerced to Hashes, we can merge them,
124 # preserving all context except the API method parameters that we're
125 # using for pagination.
126 return Google::APIClient::Reference.new(
127 Hash[self.reference].merge(:parameters => merged_parameters)