Module: ClashOfClansApi::EndpointMethods

Included in:
Api, TokenApi
Defined in:
lib/clash_of_clans_api/endpoint_methods.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



47
48
49
# File 'lib/clash_of_clans_api/endpoint_methods.rb', line 47

def self.included(klass)
	klass.extend(ClassMethods)
end

Instance Method Details

#endpoint_headersObject



7
8
9
# File 'lib/clash_of_clans_api/endpoint_methods.rb', line 7

def endpoint_headers
	{}
end

#perform_request(method, api_path, query: nil, body: nil, headers: nil) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/clash_of_clans_api/endpoint_methods.rb', line 11

def perform_request(method, api_path, query: nil, body: nil, headers: nil)
	uri = self.base_uri+api_path
	uri.query = URI.encode_www_form(query) if query
	
	Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme=='https') do |http|
		case method
		when :get
			Net::HTTP::Get
		when :post
			Net::HTTP::Post
		else
			raise ArgumentError, "Invalid method #{method.inspect}."
		end.new(uri).tap do |request|
			endpoint_headers.merge(headers || {}).each do |name, value|
				request[name] = value
			end
			
			if body
				request['Content-Type'] = 'application/json'
				request.body            = body
			end
		end.then do |request|
			http.request(request)
		end
	end
end

#transform_response(response) ⇒ Object



38
39
40
41
42
43
44
# File 'lib/clash_of_clans_api/endpoint_methods.rb', line 38

def transform_response(response)
	if response.is_a?(Net::HTTPSuccess)
		JSON.parse(response.body)
	else
		raise NoSuccessError.new(response)
	end
end