Adding batch support to new service interface
[arvados.git] / lib / google / api_client / service / stub_generator.rb
1 # Copyright 2013 Google Inc.
2 #
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
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 module Google
16   class APIClient
17     class Service
18       ##
19       # Auxiliary mixin to generate resource and method stubs.
20       # Used by the Service and Service::Resource classes to generate both
21       # top-level and nested resources and methods.
22       module StubGenerator
23         def generate_call_stubs(service, root)
24           metaclass = (class << self; self; end)
25
26           # Handle resources.
27           root.discovered_resources.each do |resource|
28             method_name = Google::INFLECTOR.underscore(resource.name).to_sym
29             if !self.respond_to?(method_name)
30               metaclass.send(:define_method, method_name) do
31                 Google::APIClient::Service::Resource.new(service, resource)
32               end
33             end
34           end
35
36           # Handle methods.
37           root.discovered_methods.each do |method|
38             method_name = Google::INFLECTOR.underscore(method.name).to_sym
39             if !self.respond_to?(method_name)
40               metaclass.send(:define_method, method_name) do |*args|
41                 if args.length > 1
42                   raise ArgumentError,
43                     "wrong number of arguments (#{args.length} for 1)"
44                 elsif !args.first.respond_to?(:to_hash) && !args.first.nil?
45                   raise ArgumentError,
46                     "expected parameter Hash, got #{args.first.class}"
47                 else
48                   return Google::APIClient::Service::Request.new(
49                     service, method, args.first
50                   )
51                 end
52               end
53             end
54           end
55         end
56       end
57     end
58   end
59 end