21700: Install Bundler system-wide in Rails postinst
[arvados.git] / sdk / ruby-google-api-client / 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 require 'active_support/inflector'
16
17 module Google
18   class APIClient
19     class Service
20       ##
21       # Auxiliary mixin to generate resource and method stubs.
22       # Used by the Service and Service::Resource classes to generate both
23       # top-level and nested resources and methods.
24       module StubGenerator
25         def generate_call_stubs(service, root)
26           metaclass = (class << self; self; end)
27
28           # Handle resources.
29           root.discovered_resources.each do |resource|
30             method_name = ActiveSupport::Inflector.underscore(resource.name).to_sym
31             if !self.respond_to?(method_name)
32               metaclass.send(:define_method, method_name) do
33                 Google::APIClient::Service::Resource.new(service, resource)
34               end
35             end
36           end
37
38           # Handle methods.
39           root.discovered_methods.each do |method|
40             method_name = ActiveSupport::Inflector.underscore(method.name).to_sym
41             if !self.respond_to?(method_name)
42               metaclass.send(:define_method, method_name) do |*args|
43                 if args.length > 1
44                   raise ArgumentError,
45                     "wrong number of arguments (#{args.length} for 1)"
46                 elsif !args.first.respond_to?(:to_hash) && !args.first.nil?
47                   raise ArgumentError,
48                     "expected parameter Hash, got #{args.first.class}"
49                 else
50                   return Google::APIClient::Service::Request.new(
51                     service, method, args.first
52                   )
53                 end
54               end
55             end
56           end
57         end
58       end
59     end
60   end
61 end