-
Notifications
You must be signed in to change notification settings - Fork 5
/
routing.rb
56 lines (46 loc) · 1.21 KB
/
routing.rb
1
2
3
4
5
6
7
8
9
10
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# frozen_string_literal: true
module Scnnr
class Routing
API_SCHEME = URI::HTTPS
API_HOST = 'api.scnnr.cubki.jp'
attr_reader :path_prefix
def initialize(path, path_prefix, params, allowed_params)
@path = path
@path_prefix = path_prefix
@queries = build_queries params, allowed_params
end
def to_url
API_SCHEME.build(
host: API_HOST,
path: self.path,
query: query_string
)
end
def queries
@queries.reject { |_, val| val.nil? }
end
def path
"/#{[self.path_prefix, @path]
.map { |value| value.sub(%r{\A/}, '').sub(%r{/\z}, '') }
.join('/')}"
end
private
def query_string
params = self.queries
return if params.empty?
params
.map { |pair| pair.map { |val| URI.encode_www_form_component val }.join('=') }
.join('&')
end
def build_queries(params, allowed_params)
{}.tap do |queries|
(allowed_params || []).each do |param|
case param.intern
when :timeout then queries[:timeout] = params[:timeout] if params[:timeout]&.positive?
else queries[param] = params[param]
end
end
end
end
end
end