-
Notifications
You must be signed in to change notification settings - Fork 150
/
generator.rb
209 lines (180 loc) · 7.99 KB
/
generator.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
module Swagger
module Docs
class Generator
DEFAULT_VER = "1.0"
DEFAULT_CONFIG = {
:api_file_path => "public/",
:base_path => "/",
:clean_directory => false,
:formatting => :pretty
}
class << self
def set_real_methods
Config.base_api_controller.send(:include, Methods) # replace impotent methods with live ones
end
def write_docs(apis = nil)
apis ||= Config.registered_apis
results = {}
set_real_methods
unless apis.empty?
apis.each do |api_version,config|
config.reverse_merge!(DEFAULT_CONFIG)
results[api_version] = write_doc(api_version, config)
end
else
results[DEFAULT_VER] = write_doc(DEFAULT_VER, DEFAULT_CONFIG)
end
results
end
def write_doc(api_version, config)
settings = get_settings(api_version, config)
create_output_paths(settings[:api_file_path])
clean_output_paths(settings[:api_file_path]) if config[:clean_directory] || false
root = { :api_version => api_version, :swagger_version => "1.2", :base_path => settings[:base_path] + "/", :apis => []}
results = {:processed => [], :skipped => []}
get_route_paths(settings[:controller_base_path]).each do |path|
ret = process_path(path, root, config, settings)
results[ret[:action]] << ret
if ret[:action] == :processed
create_resource_file(ret[:path], ret[:apis], ret[:models], settings, root, config)
debased_path = get_debased_path(ret[:path], settings[:controller_base_path])
resource_api = {
path: "#{Config.transform_path(trim_leading_slash(debased_path))}.{format}",
description: ret[:klass].swagger_config[:description]
}
root[:apis] << resource_api
end
end
camelize_keys_deep!(root)
write_to_file("#{settings[:api_file_path]}/api-docs.json", root, config)
results
end
private
def transform_spec_to_api_path(spec, controller_base_path, extension)
api_path = spec.to_s.dup
api_path.gsub!('(.:format)', extension ? ".#{extension}" : '')
api_path.gsub!(/:(\w+)/, '{\1}')
api_path.gsub!(controller_base_path, '')
trim_slashes(api_path)
end
def camelize_keys_deep!(h)
h.keys.each do |k|
ks = k.to_s.camelize(:lower)
h[ks] = h.delete k
camelize_keys_deep! h[ks] if h[ks].kind_of? Hash
if h[ks].kind_of? Array
h[ks].each do |a|
next unless a.kind_of? Hash
camelize_keys_deep! a
end
end
end
end
def trim_leading_slash(str)
return str if !str
str.gsub(/\A\/+/, '')
end
def trim_trailing_slash(str)
return str if !str
str.gsub(/\/+\z/, '')
end
def trim_slashes(str)
trim_leading_slash(trim_trailing_slash(str))
end
def get_debased_path(path, controller_base_path)
path.gsub("#{controller_base_path}", "")
end
def process_path(path, root, config, settings)
return {action: :skipped, reason: :empty_path} if path.empty?
klass = "#{path.to_s.camelize}Controller".constantize rescue nil
return {action: :skipped, path: path, reason: :klass_not_present} if !klass
return {action: :skipped, path: path, reason: :not_swagger_resource} if !klass.methods.include?(:swagger_config) or !klass.swagger_config[:controller]
apis, models = [], {}
Config.base_application.routes.routes.select{|i| i.defaults[:controller] == path}.each do |route|
ret = get_route_path_apis(path, route, klass, settings, config)
apis = apis + ret[:apis]
models.merge!(ret[:models])
end
{action: :processed, path: path, apis: apis, models: models, klass: klass}
end
def create_resource_file(path, apis, models, settings, root, config)
debased_path = get_debased_path(path, settings[:controller_base_path])
demod = "#{debased_path.to_s.camelize}".demodulize.camelize.underscore
resource_path = trim_leading_slash(debased_path.to_s.underscore)
resource = root.merge({:resource_path => "#{demod}", :apis => apis})
camelize_keys_deep!(resource)
# Add the already-normalized models to the resource.
resource = resource.merge({:models => models}) if models.present?
# write controller resource file
write_to_file(File.join(settings[:api_file_path], "#{resource_path}.json"), resource, config)
end
def get_route_path_apis(path, route, klass, settings, config)
models, apis = {}, []
action = route.defaults[:action]
verb = route.verb.source.to_s.delete('$'+'^').downcase.to_sym
return apis if !operations = klass.swagger_actions[action.to_sym]
operations = Hash[operations.map {|k, v| [k.to_s.gsub("@","").to_sym, v.respond_to?(:deep_dup) ? v.deep_dup : v.dup] }] # rename :@instance hash keys
operations[:method] = verb
operations[:nickname] = "#{path.camelize}##{action}"
api_path = transform_spec_to_api_path(route.path.spec, settings[:controller_base_path], config[:api_extension_type])
operations[:parameters] = filter_path_params(api_path, operations[:parameters]) if operations[:parameters]
apis << {:path => api_path, :operations => [operations]}
models = get_klass_models(klass)
{apis: apis, models: models}
end
def get_klass_models(klass)
models = {}
# Add any declared models to the root of the resource.
klass.swagger_models.each do |model_name, model|
formatted_model = {
id: model[:id],
required: model[:required],
properties: model[:properties],
}
formatted_model[:description] = model[:description] if model[:description]
models[model[:id]] = formatted_model
end
models
end
def get_settings(api_version, config)
base_path = trim_trailing_slash(config[:base_path] || "")
controller_base_path = trim_leading_slash(config[:controller_base_path] || "")
base_path += "/#{controller_base_path}" unless controller_base_path.empty?
api_file_path = config[:api_file_path]
settings = {
base_path: base_path,
controller_base_path: controller_base_path,
api_file_path: api_file_path
}.freeze
end
def get_route_paths(controller_base_path)
paths = Config.base_application.routes.routes.map{|i| "#{i.defaults[:controller]}" }
paths.uniq.select{|i| i.start_with?(controller_base_path)}
end
def create_output_paths(api_file_path)
FileUtils.mkdir_p(api_file_path) # recursively create out output path
end
def clean_output_paths(api_file_path)
Dir.foreach(api_file_path) do |f|
fn = File.join(api_file_path, f)
File.delete(fn) if !File.directory?(fn) and File.extname(fn) == '.json'
end
end
def write_to_file(path, structure, config={})
content = case config[:formatting]
when :pretty; JSON.pretty_generate structure
else; structure.to_json
end
FileUtils.mkdir_p File.dirname(path)
File.open(path, 'w') { |file| file.write content }
end
def filter_path_params(path, params)
params.reject do |param|
param_as_variable = "{#{param[:name]}}"
param[:param_type] == :path && !path.include?(param_as_variable)
end
end
end
end
end
end