swagger_autogenerate 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +84 -0
- data/LICENSE.txt +21 -0
- data/README.md +75 -0
- data/Rakefile +4 -0
- data/lib/config/initializers/swagger_autogenerate.rb +5 -0
- data/lib/swagger_autogenerate/swagger_public_methods.rb +50 -0
- data/lib/swagger_autogenerate/swagger_trace.rb +473 -0
- data/lib/swagger_autogenerate/version.rb +5 -0
- data/lib/swagger_autogenerate.rb +16 -0
- data/sig/swagger_autogenerate.rbs +4 -0
- data/swagger_autogenerate.gemspec +40 -0
- metadata +59 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 1adeb3bac00fabb0f8f62df4b322a3a2ee4dc0068c5c404e9533e1a0e9f75f5b
|
4
|
+
data.tar.gz: 10a0f11601d637b23378d2808a055e1140b4a79be7080b1e40ca4b5b668f2c57
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: ea65f1e69465f1deda419b6fda47d775a2935f71c8cbd1dd0b3bbdc268e777d76212c4d7b66ab43743f69fa54b303f51259f984a713ed2c95810d22e1afa0d3f
|
7
|
+
data.tar.gz: b82d945b513d0e7c9bfa7f395985659043d9bff8c0bf782cc8c91dfd4664a16d612da7575546186fb7d18907622c97eefbc7d15d43bfb9f8db0d8c5bfd24f097
|
data/CHANGELOG.md
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,84 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
6
|
+
|
7
|
+
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
8
|
+
|
9
|
+
## Our Standards
|
10
|
+
|
11
|
+
Examples of behavior that contributes to a positive environment for our community include:
|
12
|
+
|
13
|
+
* Demonstrating empathy and kindness toward other people
|
14
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
15
|
+
* Giving and gracefully accepting constructive feedback
|
16
|
+
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
|
17
|
+
* Focusing on what is best not just for us as individuals, but for the overall community
|
18
|
+
|
19
|
+
Examples of unacceptable behavior include:
|
20
|
+
|
21
|
+
* The use of sexualized language or imagery, and sexual attention or
|
22
|
+
advances of any kind
|
23
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
24
|
+
* Public or private harassment
|
25
|
+
* Publishing others' private information, such as a physical or email
|
26
|
+
address, without their explicit permission
|
27
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
28
|
+
professional setting
|
29
|
+
|
30
|
+
## Enforcement Responsibilities
|
31
|
+
|
32
|
+
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
33
|
+
|
34
|
+
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
|
35
|
+
|
36
|
+
## Scope
|
37
|
+
|
38
|
+
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
|
39
|
+
|
40
|
+
## Enforcement
|
41
|
+
|
42
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at mohammed.buraiah.1996@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
|
43
|
+
|
44
|
+
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
45
|
+
|
46
|
+
## Enforcement Guidelines
|
47
|
+
|
48
|
+
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
|
49
|
+
|
50
|
+
### 1. Correction
|
51
|
+
|
52
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
|
53
|
+
|
54
|
+
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
|
55
|
+
|
56
|
+
### 2. Warning
|
57
|
+
|
58
|
+
**Community Impact**: A violation through a single incident or series of actions.
|
59
|
+
|
60
|
+
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
|
61
|
+
|
62
|
+
### 3. Temporary Ban
|
63
|
+
|
64
|
+
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
|
65
|
+
|
66
|
+
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
|
67
|
+
|
68
|
+
### 4. Permanent Ban
|
69
|
+
|
70
|
+
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
|
71
|
+
|
72
|
+
**Consequence**: A permanent ban from any sort of public interaction within the community.
|
73
|
+
|
74
|
+
## Attribution
|
75
|
+
|
76
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
|
77
|
+
available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
78
|
+
|
79
|
+
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
|
80
|
+
|
81
|
+
[homepage]: https://www.contributor-covenant.org
|
82
|
+
|
83
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
84
|
+
https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2024 mohammedburaiah
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
13
|
+
all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
@@ -0,0 +1,75 @@
|
|
1
|
+
# SwaggerAutogenerate
|
2
|
+
automating Swagger YAML generation in Ruby on Rails offers a range of benefits for API documentation. By leveraging the power of the swagger_autogenerate gem, developers can:
|
3
|
+
1) save time and effort
|
4
|
+
2) (up to date) reducing the chances of inconsistencies between the actual API implementation and its documentation.
|
5
|
+
3) improves the overall development workflow by providing a seamless integration with testing frameworks like RSpec.
|
6
|
+
4) resulting in better communication and understanding of the APIs.
|
7
|
+
|
8
|
+
The gem automatically observes the request/response patterns during the execution of test scenarios, generating accurate Swagger YAML files that reflect the API's behavior. developers and consumers can better understand and interact with the APIs.
|
9
|
+
|
10
|
+
## Installation
|
11
|
+
|
12
|
+
1) Open your Gemfile located at ./Gemfile
|
13
|
+
2) Add the following line to the Gemfile within the appropriate group (e.g., :test):
|
14
|
+
|
15
|
+
```
|
16
|
+
group :test do
|
17
|
+
gem 'swagger_autogenerate'
|
18
|
+
end
|
19
|
+
```
|
20
|
+
3) Install the gem and add to the application's Gemfile by executing:
|
21
|
+
$ bundle install
|
22
|
+
|
23
|
+
## Configuration
|
24
|
+
|
25
|
+
To configure the swagger_autogenerate gem in your Rails application, follow these steps:
|
26
|
+
|
27
|
+
### Step 1:
|
28
|
+
1) Open the app/controllers/application_controller.rb
|
29
|
+
2) Inside the class ApplicationController block.
|
30
|
+
3) Add the following code:
|
31
|
+
```
|
32
|
+
include SwaggerAutogenerate if Rails.env.test? && ENV['SWAGGER'].present?
|
33
|
+
```
|
34
|
+
|
35
|
+
### Step 2 (optional)
|
36
|
+
1) Create a file called swagger_autogenerate.rb in the ./config/initializers
|
37
|
+
2) Open the ./config/initializers/swagger/swagger_autogenerate.rb
|
38
|
+
3) Add the following code to the swagger_autogenerate.rb
|
39
|
+
```
|
40
|
+
module SwaggerAutogenerate
|
41
|
+
class SwaggerTrace
|
42
|
+
WITH_CONFIG = true
|
43
|
+
WITH_MULTIPLE_EXAMPLES = true
|
44
|
+
WITH_EXAMPLE_DESCRIPTION = true
|
45
|
+
WITH_RESPONSE_DESCRIPTION = true
|
46
|
+
SWAGGER_ENVIRONMENT_VARIABLE = 'SWAGGER'
|
47
|
+
end
|
48
|
+
end
|
49
|
+
```
|
50
|
+
$ This file is optional and allows you to customize the behavior of the gem by providing additional options.
|
51
|
+
|
52
|
+
## Example
|
53
|
+
To generate Swagger YAML documentation for the APIs implemented in the EmployeesController class, you can follow these steps:
|
54
|
+
1) Ensure that you have the swagger_autogenerate gem installed and configured in your Rails application, as described later.
|
55
|
+
2) Create a spec file for the EmployeesController class at the path:
|
56
|
+
$ spec/your_path/employees_controller_spec.rb
|
57
|
+
This file should contain the test scenarios for each action (e.g., index, show, create) of the controller.
|
58
|
+
|
59
|
+
3)Run the spec code using the rspec command and set the environment variable SWAGGER to the desired YAML file name. For example:
|
60
|
+
```
|
61
|
+
SWAGGER='employee_apis.yaml' rspec spec/your_path/employees_controller_spec.rb
|
62
|
+
```
|
63
|
+
4) This command runs the spec file and instructs the swagger_autogenerate gem to generate Swagger YAML documentation and save it to the file named employee_apis.yaml.
|
64
|
+
5) Once the command finishes executing, you will have the Swagger YAML documentation generated based on the test scenarios in the employees_controller_spec.rb file.
|
65
|
+
|
66
|
+
### Please note
|
67
|
+
that the generated documentation will depend on the test scenarios defined in your employees_controller_spec.rb file. Make sure to have comprehensive test scenarios that cover different scenarios and expected responses for accurate and detailed Swagger documentation.
|
68
|
+
|
69
|
+
## License
|
70
|
+
|
71
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
72
|
+
|
73
|
+
## Code of Conduct
|
74
|
+
|
75
|
+
Everyone interacting in the SwaggerAutogenerate project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/swagger_autogenerate/blob/master/CODE_OF_CONDUCT.md).
|
data/Rakefile
ADDED
@@ -0,0 +1,50 @@
|
|
1
|
+
module SwaggerAutogenerate
|
2
|
+
module SwaggerPublicMethods
|
3
|
+
def response_status
|
4
|
+
{
|
5
|
+
100 => 'The initial part of the request has been received, and the client should proceed with sending the remainder of the request',
|
6
|
+
101 => 'The server agrees to switch protocols and is acknowledging the client\'s request to change the protocol being used',
|
7
|
+
200 => 'The request has succeeded',
|
8
|
+
201 => 'The request has been fulfilled, and a new resource has been created as a result. The newly created resource is returned in the response body',
|
9
|
+
202 => 'The request has been accepted for processing, but the processing has not been completed. The response may contain an estimated completion time or other status information',
|
10
|
+
204 => 'The server has successfully processed the request but does not need to return any content. It is often used for requests that don\'t require a response body, such as DELETE requests',
|
11
|
+
300 => 'The requested resource has multiple choices available, each with its own URI and representation. The client can select one of the available choices',
|
12
|
+
301 => 'The requested resource has been permanently moved to a new location, and any future references to this resource should use the new URI provided in the response',
|
13
|
+
302 => 'The requested resource has been temporarily moved to a different location. The client should use the URI specified in the response for future requests',
|
14
|
+
304 => 'The client\'s cached copy of a resource is still valid, and there is no need to transfer a new copy. The client can use its cached version',
|
15
|
+
400 => 'The server cannot understand the request due to a client error, such as malformed syntax or invalid parameters',
|
16
|
+
401 => 'The request requires user authentication. The client must provide valid credentials (e.g., username and password) to access the requested resource',
|
17
|
+
403 => 'The server understood the request, but the client does not have permission to access the requested resource',
|
18
|
+
404 => 'The requested resource could not be found on the server',
|
19
|
+
405 => 'The requested resource does not support the HTTP method used in the request (e.g., GET, POST, PUT, DELETE)',
|
20
|
+
409 => 'The request could not be completed due to a conflict with the current state of the target resource. The client may need to resolve the conflict before resubmitting the request',
|
21
|
+
422 => 'The server understands the content type of the request entity but was unable to process the contained instructions',
|
22
|
+
500 => 'The server encountered an unexpected condition that prevented it from fulfilling the request',
|
23
|
+
502 => 'The server acting as a gateway or proxy received an invalid response from an upstream server',
|
24
|
+
503 => 'The server is currently unable to handle the request due to temporary overload or maintenance. The server may provide a Retry-After header to indicate when the client can try the request again',
|
25
|
+
504 => 'The server acting as a gateway or proxy did not receive a timely response from an upstream server'
|
26
|
+
}
|
27
|
+
end
|
28
|
+
|
29
|
+
def swagger_config
|
30
|
+
{
|
31
|
+
'openapi' => '3.0.0',
|
32
|
+
'info' => {
|
33
|
+
'title' => 'title',
|
34
|
+
'description' => 'description',
|
35
|
+
'version' => '1.0.0'
|
36
|
+
},
|
37
|
+
'servers' => [],
|
38
|
+
'components' => {
|
39
|
+
'securitySchemes' => {
|
40
|
+
'locale' => {
|
41
|
+
'type' => 'apiKey',
|
42
|
+
'in' => 'query',
|
43
|
+
'name' => 'locale'
|
44
|
+
}
|
45
|
+
}
|
46
|
+
}
|
47
|
+
}
|
48
|
+
end
|
49
|
+
end
|
50
|
+
end
|
@@ -0,0 +1,473 @@
|
|
1
|
+
require_relative 'swagger_public_methods'
|
2
|
+
|
3
|
+
module SwaggerAutogenerate
|
4
|
+
class SwaggerTrace
|
5
|
+
WITH_CONFIG = true
|
6
|
+
WITH_MULTIPLE_EXAMPLES = true
|
7
|
+
WITH_EXAMPLE_DESCRIPTION = true
|
8
|
+
WITH_RESPONSE_DESCRIPTION = true
|
9
|
+
SWAGGER_ENVIRONMENT_VARIABLE = 'SWAGGER'
|
10
|
+
|
11
|
+
include SwaggerPublicMethods
|
12
|
+
|
13
|
+
def initialize(request, response)
|
14
|
+
@request = request
|
15
|
+
@response = response
|
16
|
+
@@paths = {}
|
17
|
+
end
|
18
|
+
|
19
|
+
def call
|
20
|
+
read_swaggger_trace
|
21
|
+
write_swaggger_trace
|
22
|
+
end
|
23
|
+
|
24
|
+
private
|
25
|
+
|
26
|
+
attr_reader :request, :response, :current_path, :yaml_file
|
27
|
+
|
28
|
+
# main methods
|
29
|
+
|
30
|
+
def read_swaggger_trace
|
31
|
+
path = request.path
|
32
|
+
|
33
|
+
request.path_parameters.except(:controller, :format, :action).each do |k, v|
|
34
|
+
path = path.gsub!(v, "{#{k}}")
|
35
|
+
end
|
36
|
+
|
37
|
+
@current_path = path
|
38
|
+
method = request.method.to_s.downcase
|
39
|
+
hash =
|
40
|
+
{
|
41
|
+
method => {
|
42
|
+
'tags' => tags,
|
43
|
+
'summary' => summary,
|
44
|
+
'requestBody' => request_body,
|
45
|
+
'parameters' => parameters,
|
46
|
+
'responses' => {},
|
47
|
+
'security' => security
|
48
|
+
}
|
49
|
+
}
|
50
|
+
|
51
|
+
hash[method].except!('requestBody') if hash[method]['requestBody'].blank?
|
52
|
+
paths[path.to_s] ||= {}
|
53
|
+
paths[path.to_s].merge!(hash)
|
54
|
+
end
|
55
|
+
|
56
|
+
def write_swaggger_trace
|
57
|
+
if paths[current_path][request.method.downcase].present?
|
58
|
+
paths[current_path][request.method.downcase]['responses'] = swagger_response
|
59
|
+
end
|
60
|
+
|
61
|
+
if File.exist?(swagger_location)
|
62
|
+
edit_file
|
63
|
+
else
|
64
|
+
create_file
|
65
|
+
end
|
66
|
+
end
|
67
|
+
|
68
|
+
def create_file
|
69
|
+
File.open(swagger_location, 'w') do |file|
|
70
|
+
data = WITH_CONFIG ? swagger_config : {}
|
71
|
+
data['paths'] = paths
|
72
|
+
organize_result(data['paths'])
|
73
|
+
data = data.to_hash
|
74
|
+
result = add_quotes_to_dates(YAML.dump(data))
|
75
|
+
file.write(result)
|
76
|
+
end
|
77
|
+
end
|
78
|
+
|
79
|
+
def edit_file
|
80
|
+
@yaml_file = YAML.load(
|
81
|
+
File.read(swagger_location),
|
82
|
+
aliases: true,
|
83
|
+
permitted_classes: [Symbol, Date, ActiveSupport::HashWithIndifferentAccess]
|
84
|
+
)
|
85
|
+
|
86
|
+
return create_file if yaml_file.nil? || yaml_file['paths'].nil?
|
87
|
+
|
88
|
+
yaml_file.merge!(swagger_config) if WITH_CONFIG
|
89
|
+
|
90
|
+
apply_yaml_file_changes
|
91
|
+
organize_result(yaml_file['paths'])
|
92
|
+
@yaml_file = convert_to_hash(yaml_file)
|
93
|
+
File.open(swagger_location, 'w') do |file|
|
94
|
+
result = add_quotes_to_dates(YAML.dump(yaml_file))
|
95
|
+
file.write(result)
|
96
|
+
end
|
97
|
+
end
|
98
|
+
|
99
|
+
# Helpers
|
100
|
+
|
101
|
+
def add_quotes_to_dates(string)
|
102
|
+
string = remove_quotes_in_dates(string)
|
103
|
+
string.gsub(/\b\d{4}-\d{2}-\d{2}\b/, "'\\0'")
|
104
|
+
end
|
105
|
+
|
106
|
+
def remove_quotes_in_dates(string)
|
107
|
+
string.gsub(/'(\d{4}-\d{2}-\d{2})'/, '\1')
|
108
|
+
end
|
109
|
+
|
110
|
+
def convert_to_hash(obj)
|
111
|
+
case obj
|
112
|
+
when ActiveSupport::HashWithIndifferentAccess
|
113
|
+
obj.to_hash
|
114
|
+
when Hash
|
115
|
+
obj.transform_values { |value| convert_to_hash(value) }
|
116
|
+
when Array
|
117
|
+
obj.map { |item| convert_to_hash(item) }
|
118
|
+
else
|
119
|
+
obj
|
120
|
+
end
|
121
|
+
end
|
122
|
+
|
123
|
+
def properties_data(value)
|
124
|
+
hash = {}
|
125
|
+
|
126
|
+
value.map do |k, v|
|
127
|
+
type = schema_type(v)
|
128
|
+
hash.merge!({ k => { 'type' => type, 'example' => convert_to_hash(v) } })
|
129
|
+
end
|
130
|
+
|
131
|
+
hash
|
132
|
+
end
|
133
|
+
|
134
|
+
def schema_data(value)
|
135
|
+
type = schema_type(value)
|
136
|
+
hash = { 'type' => type }
|
137
|
+
hash['properties'] = {}
|
138
|
+
hash['properties'] = properties_data(value) if type == 'object' && !value.nil?
|
139
|
+
|
140
|
+
hash
|
141
|
+
end
|
142
|
+
|
143
|
+
def set_parameters(parameters, parameter, required: false)
|
144
|
+
return if parameter.blank?
|
145
|
+
|
146
|
+
parameter.values.first.each do |key, value|
|
147
|
+
hash =
|
148
|
+
{
|
149
|
+
'name' => key.to_s,
|
150
|
+
'in' => parameter.keys.first.to_s,
|
151
|
+
'schema' => schema_data(value),
|
152
|
+
'example' => example(value)
|
153
|
+
}
|
154
|
+
|
155
|
+
hash['required'] = required if required
|
156
|
+
hash.except!('example') if hash['example'].blank?
|
157
|
+
|
158
|
+
parameters.push(hash)
|
159
|
+
end
|
160
|
+
end
|
161
|
+
|
162
|
+
def request_body
|
163
|
+
content_body(request.request_parameters) if request.request_parameters.present?
|
164
|
+
end
|
165
|
+
|
166
|
+
def tags
|
167
|
+
[ENV['tag'] || controller_name]
|
168
|
+
end
|
169
|
+
|
170
|
+
def summary
|
171
|
+
URI.parse(request.path).path
|
172
|
+
end
|
173
|
+
|
174
|
+
def response_description
|
175
|
+
response_status[response.status]
|
176
|
+
end
|
177
|
+
|
178
|
+
def swagger_response
|
179
|
+
hash = {}
|
180
|
+
begin
|
181
|
+
swagger_response = JSON.parse(response.body)
|
182
|
+
rescue JSON::ParserError
|
183
|
+
swagger_response = { 'file' => 'file/data' }
|
184
|
+
end
|
185
|
+
|
186
|
+
hash['description'] = response_description if WITH_RESPONSE_DESCRIPTION
|
187
|
+
hash['headers'] = {} # response.headers
|
188
|
+
hash['content'] = content_json_example(swagger_response)
|
189
|
+
|
190
|
+
{
|
191
|
+
response.status.to_s => hash
|
192
|
+
}
|
193
|
+
end
|
194
|
+
|
195
|
+
def convert_to_multipart(payload)
|
196
|
+
payload.each do |key, value|
|
197
|
+
if value.is_a?(Hash)
|
198
|
+
payload_keys.push(key)
|
199
|
+
convert_to_multipart(value)
|
200
|
+
else
|
201
|
+
keys = payload_keys.clone
|
202
|
+
first_key = keys.shift
|
203
|
+
keys.each { |inner_key| first_key = "#{first_key}[#{inner_key}]" }
|
204
|
+
first_key = "#{first_key}[#{key}]"
|
205
|
+
|
206
|
+
payload_hash.merge!({ first_key => { 'type' => schema_type(value), 'example' => example(value) } })
|
207
|
+
end
|
208
|
+
end
|
209
|
+
end
|
210
|
+
|
211
|
+
def content_form_data(data)
|
212
|
+
convert_to_multipart(data)
|
213
|
+
converted_payload = @payload_hash.clone
|
214
|
+
@payload_hash = nil
|
215
|
+
@payload_keys = nil
|
216
|
+
|
217
|
+
{
|
218
|
+
'multipart/form-data' => {
|
219
|
+
'schema' => {
|
220
|
+
'type' => 'object',
|
221
|
+
'properties' => converted_payload
|
222
|
+
}
|
223
|
+
}
|
224
|
+
}
|
225
|
+
end
|
226
|
+
|
227
|
+
def content_body(data)
|
228
|
+
hash = {}
|
229
|
+
# hash.merge!(content_json(data))
|
230
|
+
hash.merge!(content_form_data(data))
|
231
|
+
|
232
|
+
{ 'content' => hash }
|
233
|
+
end
|
234
|
+
|
235
|
+
def number?(value)
|
236
|
+
true if Float(value)
|
237
|
+
rescue StandardError
|
238
|
+
false
|
239
|
+
end
|
240
|
+
|
241
|
+
def schema_type(value)
|
242
|
+
return 'integer' if number?(value)
|
243
|
+
return 'boolean' if (value.try(:downcase) == 'true') || (value.try(:downcase) == 'false')
|
244
|
+
return 'string' if value.instance_of?(String) || value.instance_of?(Symbol)
|
245
|
+
return 'array' if value.instance_of?(Array)
|
246
|
+
|
247
|
+
'object'
|
248
|
+
end
|
249
|
+
|
250
|
+
def example(value)
|
251
|
+
return value.to_i if number?(value)
|
252
|
+
return convert_to_date(value) if value.instance_of?(String) && is_valid_date?(value)
|
253
|
+
return value if value.instance_of?(String) || value.instance_of?(Symbol)
|
254
|
+
|
255
|
+
nil
|
256
|
+
end
|
257
|
+
|
258
|
+
def is_valid_date?(string)
|
259
|
+
Date.parse(string)
|
260
|
+
true
|
261
|
+
rescue ArgumentError
|
262
|
+
false
|
263
|
+
end
|
264
|
+
|
265
|
+
def convert_to_date(string)
|
266
|
+
datetime = DateTime.parse(string)
|
267
|
+
datetime.strftime('%Y-%m-%d')
|
268
|
+
rescue ArgumentError
|
269
|
+
string
|
270
|
+
end
|
271
|
+
|
272
|
+
# parameters
|
273
|
+
|
274
|
+
def parameters
|
275
|
+
parameters = []
|
276
|
+
|
277
|
+
set_parameters(parameters, path_parameters, required: true)
|
278
|
+
set_parameters(parameters, request_parameters) if request.request_parameters.blank?
|
279
|
+
set_parameters(parameters, query_parameters)
|
280
|
+
|
281
|
+
parameters
|
282
|
+
end
|
283
|
+
|
284
|
+
def request_parameters
|
285
|
+
{ body: request.request_parameters }
|
286
|
+
end
|
287
|
+
|
288
|
+
def query_parameters
|
289
|
+
{ query: request.query_parameters }
|
290
|
+
end
|
291
|
+
|
292
|
+
def path_parameters
|
293
|
+
{ path: request.path_parameters.except(:controller, :format, :action) }
|
294
|
+
end
|
295
|
+
|
296
|
+
# Static
|
297
|
+
|
298
|
+
def paths
|
299
|
+
@@paths ||= {}
|
300
|
+
end
|
301
|
+
|
302
|
+
def security
|
303
|
+
[
|
304
|
+
'org_slug' => [],
|
305
|
+
'locale' => []
|
306
|
+
]
|
307
|
+
end
|
308
|
+
|
309
|
+
def controller_name
|
310
|
+
request.params['controller'].split('/').last.to_s
|
311
|
+
end
|
312
|
+
|
313
|
+
def swagger_location
|
314
|
+
return @swagger_location if instance_variable_defined?(:@swagger_location)
|
315
|
+
|
316
|
+
if ENV[SWAGGER_ENVIRONMENT_VARIABLE].include?('.yaml') || ENV[SWAGGER_ENVIRONMENT_VARIABLE].include?('.yml')
|
317
|
+
@swagger_location = Rails.root.join(ENV.fetch(SWAGGER_ENVIRONMENT_VARIABLE, nil).to_s).to_s
|
318
|
+
else
|
319
|
+
directory_path = Rails.root.join(ENV.fetch(SWAGGER_ENVIRONMENT_VARIABLE, nil).to_s).to_s
|
320
|
+
FileUtils.mkdir_p(directory_path) unless File.directory?(directory_path)
|
321
|
+
@swagger_location = "#{directory_path}/#{tags.first}.yaml"
|
322
|
+
end
|
323
|
+
end
|
324
|
+
|
325
|
+
def content_json(data)
|
326
|
+
{
|
327
|
+
'application/json' => {
|
328
|
+
'schema' => { 'type' => 'object' },
|
329
|
+
'example' => data
|
330
|
+
}
|
331
|
+
}
|
332
|
+
end
|
333
|
+
|
334
|
+
def content_json_example(data)
|
335
|
+
hash = {
|
336
|
+
'application/json' => {
|
337
|
+
'schema' => { 'type' => 'object' },
|
338
|
+
'examples' => {
|
339
|
+
'example-0' => {
|
340
|
+
'value' => data
|
341
|
+
}
|
342
|
+
}
|
343
|
+
}
|
344
|
+
}
|
345
|
+
hash['application/json']['examples']['example-0']['description'] = "payload => #{example_description}" if WITH_EXAMPLE_DESCRIPTION && !example_description.empty?
|
346
|
+
|
347
|
+
hash
|
348
|
+
end
|
349
|
+
|
350
|
+
def example_description
|
351
|
+
body_ = request_parameters.values.first.present? ? { 'body_params' => request_parameters.values.first&.as_json }: nil
|
352
|
+
query_ = query_parameters.values.first.present? ? { 'query_params' => query_parameters.values.first&.as_json } : nil
|
353
|
+
path_ = path_parameters.values.first.present? ? { 'path_params' => path_parameters.values.first&.as_json }: nil
|
354
|
+
|
355
|
+
[path_, query_, body_].
|
356
|
+
compact.
|
357
|
+
to_s.
|
358
|
+
gsub('-', '/').
|
359
|
+
gsub("'", '').
|
360
|
+
gsub("=>", ': ')
|
361
|
+
end
|
362
|
+
|
363
|
+
def json_example_plus_one(string)
|
364
|
+
if string =~ /(\d+)$/
|
365
|
+
modified_numeric_part = $1.to_i + 1
|
366
|
+
string.sub(/(\d+)$/, modified_numeric_part.to_s)
|
367
|
+
else
|
368
|
+
string
|
369
|
+
end
|
370
|
+
end
|
371
|
+
|
372
|
+
def payload_keys
|
373
|
+
@payload_keys ||= []
|
374
|
+
end
|
375
|
+
|
376
|
+
def payload_hash
|
377
|
+
@payload_hash ||= {}
|
378
|
+
end
|
379
|
+
|
380
|
+
def new_example
|
381
|
+
current_example = swagger_response[response.status.to_s]['content']['application/json']['examples']['example-0']
|
382
|
+
old_examples = old_paths[current_path][request.method.downcase]['responses'][response.status.to_s]['content']['application/json']['examples']
|
383
|
+
|
384
|
+
unless old_examples.value?(current_example)
|
385
|
+
last_example = json_example_plus_one(old_examples.keys.last)
|
386
|
+
last_example ||= 'example-0'
|
387
|
+
last_example = 'example-0' unless WITH_MULTIPLE_EXAMPLES
|
388
|
+
yaml_file['paths'][current_path][request.method.downcase]['responses'][response.status.to_s]['content']['application/json']['examples'][last_example] = current_example
|
389
|
+
end
|
390
|
+
|
391
|
+
true
|
392
|
+
end
|
393
|
+
|
394
|
+
def apply_yaml_file_changes
|
395
|
+
(check_path || check_method || check_status) &&
|
396
|
+
(check_parameters || check_parameter) &&
|
397
|
+
(check_request_bodys || check_request_body)
|
398
|
+
end
|
399
|
+
|
400
|
+
def old_paths
|
401
|
+
yaml_file['paths']
|
402
|
+
end
|
403
|
+
|
404
|
+
# checks
|
405
|
+
|
406
|
+
def organize_result(current_paths)
|
407
|
+
new_hash = {
|
408
|
+
'tags' => tags,
|
409
|
+
'summary' => summary
|
410
|
+
}
|
411
|
+
new_hash['parameters'] = current_paths[current_path][request.method.downcase]['parameters'] if current_paths[current_path][request.method.downcase]['parameters']
|
412
|
+
new_hash['requestBody'] = current_paths[current_path][request.method.downcase]['requestBody'] if current_paths[current_path][request.method.downcase]['requestBody']
|
413
|
+
new_hash['responses'] = current_paths[current_path][request.method.downcase]['responses']
|
414
|
+
new_hash['security'] = security
|
415
|
+
|
416
|
+
current_paths[current_path][request.method.downcase] = new_hash
|
417
|
+
end
|
418
|
+
|
419
|
+
def check_path
|
420
|
+
unless old_paths.key?(current_path)
|
421
|
+
yaml_file['paths'].merge!({ current_path => paths[current_path] })
|
422
|
+
end
|
423
|
+
end
|
424
|
+
|
425
|
+
def check_method
|
426
|
+
unless old_paths[current_path].key?(request.method.downcase)
|
427
|
+
yaml_file['paths'][current_path][request.method.downcase] = { 'responses' => swagger_response }
|
428
|
+
end
|
429
|
+
end
|
430
|
+
|
431
|
+
def check_status
|
432
|
+
if old_paths[current_path][request.method.downcase]['responses'].present?
|
433
|
+
if old_paths[current_path][request.method.downcase]['responses']&.key?(response.status.to_s)
|
434
|
+
new_example
|
435
|
+
else
|
436
|
+
yaml_file['paths'][current_path][request.method.downcase]['responses'].merge!(swagger_response)
|
437
|
+
end
|
438
|
+
else
|
439
|
+
yaml_file['paths'][current_path][request.method.downcase]['responses'] = swagger_response
|
440
|
+
end
|
441
|
+
end
|
442
|
+
|
443
|
+
def check_parameters
|
444
|
+
if old_paths[current_path][request.method.downcase]['parameters'].blank?
|
445
|
+
yaml_file['paths'][current_path][request.method.downcase]['parameters'] = paths[current_path][request.method.downcase]['parameters']
|
446
|
+
end
|
447
|
+
end
|
448
|
+
|
449
|
+
def check_parameter
|
450
|
+
param_names = paths[current_path][request.method.downcase]['parameters'].pluck('name') - yaml_file['paths'][current_path][request.method.downcase]['parameters'].pluck('name')
|
451
|
+
param_names.each do |param_name|
|
452
|
+
param = paths[current_path][request.method.downcase]['parameters'].find { |parameter| parameter['name'] == param_name }
|
453
|
+
yaml_file['paths'][current_path][request.method.downcase]['parameters'].push(param)
|
454
|
+
end
|
455
|
+
end
|
456
|
+
|
457
|
+
def check_request_bodys
|
458
|
+
if paths[current_path][request.method.downcase]['requestBody'].present? && old_paths[current_path][request.method.downcase]['requestBody'].nil?
|
459
|
+
yaml_file['paths'][current_path][request.method.downcase]['requestBody'] = paths[current_path][request.method.downcase]['requestBody']
|
460
|
+
end
|
461
|
+
end
|
462
|
+
|
463
|
+
def check_request_body
|
464
|
+
if paths[current_path][request.method.downcase]['requestBody'].present?
|
465
|
+
param_names = paths[current_path][request.method.downcase]['requestBody']['content']['multipart/form-data']['schema']['properties'].keys - yaml_file['paths'][current_path][request.method.downcase]['requestBody']['content']['multipart/form-data']['schema']['properties'].keys
|
466
|
+
param_names.each do |param_name|
|
467
|
+
param = paths[current_path][request.method.downcase]['requestBody']['content']['multipart/form-data']['schema']['properties'].select { |parameter| parameter == param_name }
|
468
|
+
yaml_file['paths'][current_path][request.method.downcase]['requestBody']['content']['multipart/form-data']['schema']['properties'].merge!(param)
|
469
|
+
end
|
470
|
+
end
|
471
|
+
end
|
472
|
+
end
|
473
|
+
end
|
@@ -0,0 +1,16 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module SwaggerAutogenerate
|
4
|
+
extend ::ActiveSupport::Concern
|
5
|
+
require_relative 'swagger_autogenerate/swagger_trace.rb'
|
6
|
+
|
7
|
+
included do
|
8
|
+
if defined?(Rails) && Rails.env.test? && ENV[SwaggerTrace::SWAGGER_ENVIRONMENT_VARIABLE].present?
|
9
|
+
def process_action(*args)
|
10
|
+
super
|
11
|
+
|
12
|
+
SwaggerTrace.new(request, response).call
|
13
|
+
end
|
14
|
+
end
|
15
|
+
end
|
16
|
+
end
|
@@ -0,0 +1,40 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "lib/swagger_autogenerate/version"
|
4
|
+
|
5
|
+
Gem::Specification.new do |spec|
|
6
|
+
spec.name = "swagger_autogenerate"
|
7
|
+
spec.version = SwaggerAutogenerate::VERSION
|
8
|
+
spec.authors = ["MohammedBuraiah"]
|
9
|
+
spec.email = ["mohammed.buraiah.1996@gmail.com"]
|
10
|
+
|
11
|
+
spec.summary = "Write a short summary, because RubyGems requires one."
|
12
|
+
spec.description = "Write a longer description or delete this line."
|
13
|
+
spec.homepage = "https://github.com/MohammedBuraiah/swagger_autogenerate"
|
14
|
+
spec.license = "MIT"
|
15
|
+
spec.required_ruby_version = ">= 2.6.0"
|
16
|
+
|
17
|
+
spec.metadata["allowed_push_host"] = "https://rubygems.org"
|
18
|
+
|
19
|
+
spec.metadata["homepage_uri"] = spec.homepage
|
20
|
+
spec.metadata["source_code_uri"] = "https://github.com/MohammedBuraiah/swagger_autogenerate"
|
21
|
+
spec.metadata["changelog_uri"] = "https://github.com/MohammedBuraiah/swagger_autogenerate"
|
22
|
+
|
23
|
+
# Specify which files should be added to the gem when it is released.
|
24
|
+
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
|
25
|
+
spec.files = Dir.chdir(__dir__) do
|
26
|
+
`git ls-files -z`.split("\x0").reject do |f|
|
27
|
+
(File.expand_path(f) == __FILE__) ||
|
28
|
+
f.start_with?(*%w[bin/ test/ spec/ features/ .git appveyor Gemfile])
|
29
|
+
end
|
30
|
+
end
|
31
|
+
spec.bindir = "exe"
|
32
|
+
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
|
33
|
+
spec.require_paths = ["lib"]
|
34
|
+
|
35
|
+
# Uncomment to register a new dependency of your gem
|
36
|
+
# spec.add_dependency "example-gem", "~> 1.0"
|
37
|
+
|
38
|
+
# For more information and examples about making a new gem, check out our
|
39
|
+
# guide at: https://bundler.io/guides/creating_gem.html
|
40
|
+
end
|
metadata
ADDED
@@ -0,0 +1,59 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: swagger_autogenerate
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- MohammedBuraiah
|
8
|
+
autorequire:
|
9
|
+
bindir: exe
|
10
|
+
cert_chain: []
|
11
|
+
date: 2024-05-27 00:00:00.000000000 Z
|
12
|
+
dependencies: []
|
13
|
+
description: Write a longer description or delete this line.
|
14
|
+
email:
|
15
|
+
- mohammed.buraiah.1996@gmail.com
|
16
|
+
executables: []
|
17
|
+
extensions: []
|
18
|
+
extra_rdoc_files: []
|
19
|
+
files:
|
20
|
+
- CHANGELOG.md
|
21
|
+
- CODE_OF_CONDUCT.md
|
22
|
+
- LICENSE.txt
|
23
|
+
- README.md
|
24
|
+
- Rakefile
|
25
|
+
- lib/config/initializers/swagger_autogenerate.rb
|
26
|
+
- lib/swagger_autogenerate.rb
|
27
|
+
- lib/swagger_autogenerate/swagger_public_methods.rb
|
28
|
+
- lib/swagger_autogenerate/swagger_trace.rb
|
29
|
+
- lib/swagger_autogenerate/version.rb
|
30
|
+
- sig/swagger_autogenerate.rbs
|
31
|
+
- swagger_autogenerate.gemspec
|
32
|
+
homepage: https://github.com/MohammedBuraiah/swagger_autogenerate
|
33
|
+
licenses:
|
34
|
+
- MIT
|
35
|
+
metadata:
|
36
|
+
allowed_push_host: https://rubygems.org
|
37
|
+
homepage_uri: https://github.com/MohammedBuraiah/swagger_autogenerate
|
38
|
+
source_code_uri: https://github.com/MohammedBuraiah/swagger_autogenerate
|
39
|
+
changelog_uri: https://github.com/MohammedBuraiah/swagger_autogenerate
|
40
|
+
post_install_message:
|
41
|
+
rdoc_options: []
|
42
|
+
require_paths:
|
43
|
+
- lib
|
44
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
45
|
+
requirements:
|
46
|
+
- - ">="
|
47
|
+
- !ruby/object:Gem::Version
|
48
|
+
version: 2.6.0
|
49
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
50
|
+
requirements:
|
51
|
+
- - ">="
|
52
|
+
- !ruby/object:Gem::Version
|
53
|
+
version: '0'
|
54
|
+
requirements: []
|
55
|
+
rubygems_version: 3.4.19
|
56
|
+
signing_key:
|
57
|
+
specification_version: 4
|
58
|
+
summary: Write a short summary, because RubyGems requires one.
|
59
|
+
test_files: []
|