rest-api-generator 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: d5f141a24ca9cc9e364aec03cdcf46eb3e2bee8cb36cbc120b8034c8ca7fad52
4
+ data.tar.gz: 6f6410abc9657e49c10cd9a9654a0e59360128aa1990a7acdbde26485ce9806f
5
+ SHA512:
6
+ metadata.gz: 5130c55d992d388cb807642b0680983ef9fbf023d930d4182ff4af257c7209edb9dead5d4322d0d32a8eedc4b1d9e05a084d04c7735ac471c27ff34c4f984a63
7
+ data.tar.gz: 4172cf89cbff2f8ddc5216f174066fa1ccac17f7462b697103be6e624b0acd94c3114e84e96b4891dd6a6aa9151dfcb078030f6cbe23f84ed605c90f8eba6e98
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,23 @@
1
+ AllCops:
2
+ NewCops: enable
3
+ TargetRubyVersion: 2.6
4
+
5
+ Style/StringLiterals:
6
+ Enabled: true
7
+ EnforcedStyle: double_quotes
8
+
9
+ Style/StringLiteralsInInterpolation:
10
+ Enabled: true
11
+ EnforcedStyle: double_quotes
12
+
13
+ Style/Documentation:
14
+ Enabled: false
15
+
16
+ Layout/LineLength:
17
+ Max: 120
18
+
19
+ Metrics/MethodLength:
20
+ Max: 17
21
+
22
+ Metrics/AbcSize:
23
+ Max: 25
@@ -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 pedro_aduarte@aluno.unb.br. 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/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in rest-api-generator.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 1.21"
data/Gemfile.lock ADDED
@@ -0,0 +1,107 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ rest-api-generator (0.1.0)
5
+ railties (>= 5.0.0)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ actionpack (7.0.2.4)
11
+ actionview (= 7.0.2.4)
12
+ activesupport (= 7.0.2.4)
13
+ rack (~> 2.0, >= 2.2.0)
14
+ rack-test (>= 0.6.3)
15
+ rails-dom-testing (~> 2.0)
16
+ rails-html-sanitizer (~> 1.0, >= 1.2.0)
17
+ actionview (7.0.2.4)
18
+ activesupport (= 7.0.2.4)
19
+ builder (~> 3.1)
20
+ erubi (~> 1.4)
21
+ rails-dom-testing (~> 2.0)
22
+ rails-html-sanitizer (~> 1.1, >= 1.2.0)
23
+ activesupport (7.0.2.4)
24
+ concurrent-ruby (~> 1.0, >= 1.0.2)
25
+ i18n (>= 1.6, < 2)
26
+ minitest (>= 5.1)
27
+ tzinfo (~> 2.0)
28
+ ast (2.4.2)
29
+ builder (3.2.4)
30
+ concurrent-ruby (1.1.10)
31
+ crass (1.0.6)
32
+ diff-lcs (1.5.0)
33
+ erubi (1.10.0)
34
+ i18n (1.10.0)
35
+ concurrent-ruby (~> 1.0)
36
+ loofah (2.17.0)
37
+ crass (~> 1.0.2)
38
+ nokogiri (>= 1.5.9)
39
+ method_source (1.0.0)
40
+ minitest (5.15.0)
41
+ nokogiri (1.13.5-x86_64-linux)
42
+ racc (~> 1.4)
43
+ parallel (1.22.1)
44
+ parser (3.1.2.0)
45
+ ast (~> 2.4.1)
46
+ racc (1.6.0)
47
+ rack (2.2.3)
48
+ rack-test (1.1.0)
49
+ rack (>= 1.0, < 3)
50
+ rails-dom-testing (2.0.3)
51
+ activesupport (>= 4.2.0)
52
+ nokogiri (>= 1.6)
53
+ rails-html-sanitizer (1.4.2)
54
+ loofah (~> 2.3)
55
+ railties (7.0.2.4)
56
+ actionpack (= 7.0.2.4)
57
+ activesupport (= 7.0.2.4)
58
+ method_source
59
+ rake (>= 12.2)
60
+ thor (~> 1.0)
61
+ zeitwerk (~> 2.5)
62
+ rainbow (3.1.1)
63
+ rake (13.0.6)
64
+ regexp_parser (2.3.1)
65
+ rexml (3.2.5)
66
+ rspec (3.11.0)
67
+ rspec-core (~> 3.11.0)
68
+ rspec-expectations (~> 3.11.0)
69
+ rspec-mocks (~> 3.11.0)
70
+ rspec-core (3.11.0)
71
+ rspec-support (~> 3.11.0)
72
+ rspec-expectations (3.11.0)
73
+ diff-lcs (>= 1.2.0, < 2.0)
74
+ rspec-support (~> 3.11.0)
75
+ rspec-mocks (3.11.1)
76
+ diff-lcs (>= 1.2.0, < 2.0)
77
+ rspec-support (~> 3.11.0)
78
+ rspec-support (3.11.0)
79
+ rubocop (1.28.2)
80
+ parallel (~> 1.10)
81
+ parser (>= 3.1.0.0)
82
+ rainbow (>= 2.2.2, < 4.0)
83
+ regexp_parser (>= 1.8, < 3.0)
84
+ rexml
85
+ rubocop-ast (>= 1.17.0, < 2.0)
86
+ ruby-progressbar (~> 1.7)
87
+ unicode-display_width (>= 1.4.0, < 3.0)
88
+ rubocop-ast (1.17.0)
89
+ parser (>= 3.1.1.0)
90
+ ruby-progressbar (1.11.0)
91
+ thor (1.2.1)
92
+ tzinfo (2.0.4)
93
+ concurrent-ruby (~> 1.0)
94
+ unicode-display_width (2.1.0)
95
+ zeitwerk (2.5.4)
96
+
97
+ PLATFORMS
98
+ x86_64-linux
99
+
100
+ DEPENDENCIES
101
+ rake (~> 13.0)
102
+ rest-api-generator!
103
+ rspec (~> 3.0)
104
+ rubocop (~> 1.21)
105
+
106
+ BUNDLED WITH
107
+ 2.3.3
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 PedroAugustoRamalhoDuarte
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,121 @@
1
+ # RestApiGenerator
2
+
3
+ This gem works as a scaffold to generate an endpoint, it generates:
4
+
5
+ <ul>
6
+ <li> Model </li>
7
+ <li> Migration </li>
8
+ <li> Routes (resource) </li>
9
+ <li> Controller </li>
10
+ <li> Spec test of controller </li>
11
+ <li> Factory bot </li>
12
+ </ul>
13
+
14
+ the commnad its simmilar to the model generator "rails g model model_name attributes", in fact it invokes this generator to genrate the model and migration file
15
+
16
+ ## Installation
17
+
18
+ Add this line to your application's Gemfile:
19
+
20
+ ```ruby
21
+ gem 'rest-api-generator'
22
+ ```
23
+
24
+ And then execute:
25
+
26
+ $ bundle install
27
+
28
+ Or install it yourself as:
29
+
30
+ $ gem install rest-api-generator
31
+
32
+ ## Requirements
33
+ You need to have installed in your application rspec and factory bot
34
+
35
+ <ul>
36
+ <li>Rspec: https://github.com/rspec/rspec-rails</li>
37
+ <li>Factory bot: https://github.com/thoughtbot/factory_bot_rails</li>
38
+ </ul>
39
+
40
+ then inside your folder app/spec create a new folder called "requests", that's where your tests will be generated
41
+
42
+ ## Usage
43
+ ### Run command
44
+ $ rails g generator table_name attributes
45
+
46
+ ************************************************************************************
47
+ #### Model
48
+ this will generate a table and a migration with the table name and it's attribute, it invokes the model generator
49
+
50
+ ************************************************************************************
51
+ #### Endpoint
52
+ It will genrate a controller CarsController that has the methods
53
+
54
+ ##### Create
55
+ saves instance of generated model to database and return json of instance with status ok
56
+
57
+ ##### Update
58
+ updates instance of generated modelfrom database and return json of instance with status ok
59
+
60
+ ##### Delete
61
+ deletes instance of generated model from database
62
+
63
+ ##### Show
64
+ returns JSON instance of generated model from database with status ok
65
+
66
+ ##### Index
67
+ returns JSON instance of generated model from database with status ok
68
+
69
+
70
+ create and update will have permitted params defined by the attributes defined in the command (except if the attribute is type reference)
71
+ ************************************************************************************
72
+ ### Spec
73
+
74
+ ##### Create
75
+ checks if instance was saved in database
76
+
77
+ ##### Update
78
+ checks if instance was updated in database ok
79
+
80
+ ##### Delete
81
+ checks if instance was deleted from database
82
+
83
+ ##### Show
84
+ check if status ok
85
+
86
+ ##### Index
87
+ check if status ok
88
+
89
+ ************************************************************************************
90
+ ### Factory
91
+ The factory will be generated with it's custom generator, defined in the instalation of the factory-bot
92
+
93
+ ************************************************************************************
94
+ ### Routes
95
+ the routes generated are the basic resources routes:
96
+ table_name: resources
97
+
98
+ ************************************************************************************
99
+ ### Scope
100
+ It's possible to add flag in the command to generate an endpoint with a parent
101
+ $ rails g generator table_name attributes --scope father_name
102
+
103
+ the only thing this won't genrate it's the nested routes, but it will generate all the previous files mentioned just liek a scaffold
104
+
105
+ ## Development
106
+
107
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
108
+
109
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
110
+
111
+ ## Contributing
112
+
113
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/rest-api-generator. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/rest-api-generator/blob/master/CODE_OF_CONDUCT.md).
114
+
115
+ ## License
116
+
117
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
118
+
119
+ ## Code of Conduct
120
+
121
+ Everyone interacting in the Rest::Api::Generator project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/rest-api-generator/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "rest_api_generator"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,8 @@
1
+ Description:
2
+ Explain the generator
3
+
4
+ Example:
5
+ bin/rails generate rest_api_generator:resource Tag name:string
6
+
7
+ This will create:
8
+ what/will/it/create
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RestApiGenerator
4
+ module Helpers
5
+ attr_accessor :options, :attributes
6
+
7
+ private
8
+
9
+ def model_columns_for_attributes
10
+ class_name.singularize.constantize.columns.reject do |column|
11
+ column.name.to_s =~ /^(id|user_id|created_at|updated_at)$/
12
+ end
13
+ end
14
+
15
+ def editable_attributes
16
+ @editable_attributes ||= model_columns_for_attributes.map do |column|
17
+ Rails::Generators::GeneratedAttribute.new(column.name.to_s, column.type.to_s)
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+ require "generators/rest_api_generator/helpers"
5
+ module RestApiGenerator
6
+ class ResourceGenerator < Rails::Generators::NamedBase
7
+ include Helpers
8
+ source_root File.expand_path("templates", __dir__)
9
+
10
+ argument :attributes, type: :array, default: [], banner: "field[:type][:index] field[:type][:index]"
11
+ class_option :scope, type: :string, default: ""
12
+
13
+ API_CONTROLLER_DIR_PATH = "app/controllers"
14
+ API_TEST_DIR_PATH = "spec/requests"
15
+
16
+ def create_service_file
17
+ Rails::Generators.invoke("model", [file_name, build_model_attributes])
18
+ if options["scope"].empty?
19
+ controller_path = "#{API_CONTROLLER_DIR_PATH}/#{file_name.pluralize}_controller.rb"
20
+ controller_test_path = "#{API_TEST_DIR_PATH}/#{file_name.pluralize}_controller_spec.rb"
21
+ template "rest_api_controller.rb", controller_path
22
+ template "rest_api_spec.rb", controller_test_path
23
+ routes_string = "resources :#{file_name.pluralize}"
24
+ route routes_string
25
+ else
26
+ scope_path = options["scope"].pluralize
27
+ controller_path = "#{API_CONTROLLER_DIR_PATH}/#{scope_path}/#{file_name.pluralize}_controller.rb"
28
+ controller_test_path = "#{API_TEST_DIR_PATH}/#{scope_path}/#{file_name.pluralize}_controller_spec.rb"
29
+ template "child_api_controller.rb", controller_path
30
+ template "child_api_spec.rb", controller_test_path
31
+ end
32
+ end
33
+
34
+ private
35
+
36
+ def build_model_attributes
37
+ model_attributes = []
38
+ attributes.each do |attribute|
39
+ model_attributes << "#{attribute.name}:#{attribute.type}"
40
+ end
41
+ model_attributes
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,42 @@
1
+ class <%= class_name.pluralize %>Controller < ApplicationController
2
+ before_action :set_<%= options['scope'].downcase %>
3
+ before_action :set_<%= singular_name %>, only: %i[ show update destroy ]
4
+
5
+ def index
6
+ @<%= plural_name %> = @<%= options['scope'].downcase %>.<%= plural_name %>
7
+ render json: @<%= plural_name %>, status: :ok
8
+ end
9
+
10
+ def show
11
+ render json: @<%= singular_name %>, status: :ok
12
+ end
13
+
14
+ def create
15
+ @<%= singular_name %> = @<%= options['scope'].downcase %>.<%= plural_name %>.create!(<%= singular_name %>_params)
16
+ render json: @<%= singular_name %>, status: :created
17
+ end
18
+
19
+ def update
20
+ @<%= singular_name %>.update!(<%= singular_name %>_params)
21
+ render json: @<%= singular_name %>, status: :ok
22
+ end
23
+
24
+ def destroy
25
+ @<%= singular_name %>.destroy!
26
+ end
27
+
28
+
29
+ private
30
+
31
+ def set_<%= options['scope'].downcase %>
32
+ @<%= options['scope'].downcase %> = <%= options['scope'] %>.find(params[:<%= options['scope'].downcase %>_id])
33
+ end
34
+
35
+ def set_<%= singular_name %>
36
+ @<%= singular_name %> = @<%= options['scope'].downcase %>.<%= plural_name %>.find(params[:id])
37
+ end
38
+
39
+ def <%= singular_name %>_params
40
+ params.require(:<%= singular_name %>).permit(<%= attributes.map { |a| ':' + a.name }.join(', ') %>)
41
+ end
42
+ end
@@ -0,0 +1,59 @@
1
+ require 'rails_helper'
2
+
3
+ RSpec.describe "<%=class_name %>", type: :request do
4
+ let(:valid_attributes) { attributes_for(:<%= singular_table_name %>) }
5
+
6
+ describe "POST /<%= plural_name%>" do
7
+ context "with valid parameters" do
8
+ it "creates a new <%=singular_name %>" do
9
+ <%= options['scope'].downcase %> = create(:<%= options['scope'].downcase %>)
10
+ expect do
11
+ post "/<%= options['scope'].downcase.pluralize %>/#{<%= options['scope'].downcase %>.id}/<%= plural_name %>",
12
+ params: { <%= singular_name %>: valid_attributes }
13
+ end.to change(<%= class_name %>, :count).by(1)
14
+ end
15
+ end
16
+ end
17
+
18
+ describe "PATCH /<%= plural_name %>" do
19
+ let(:<%= options['scope'].downcase %>) {create(:<%= options['scope'].downcase %>)}
20
+ let(:<%= singular_table_name %>) { create(:<%=singular_table_name %>, <%= options['scope'].downcase %>: <%= options['scope'].downcase %>)}
21
+
22
+ it "updates an <%=singular_name %>" do
23
+ patch "/<%= options['scope'].downcase.pluralize %>/#{<%= options['scope'].downcase %>.id}/<%=plural_name %>/#{<%= singular_name %>.id}",
24
+ params: { <%= singular_name %>: valid_attributes }
25
+ expect(response).to have_http_status(:success)
26
+ end
27
+ end
28
+
29
+ describe "DELETE /<%= singular_name %>" do
30
+ let(:<%= options['scope'].downcase %>) {create(:<%= options['scope'].downcase %>)}
31
+
32
+ it "deletes an <%=singular_name %>" do
33
+ <%= singular_table_name %> = create(:<%=singular_table_name %>, <%= options['scope'].downcase %>: <%= options['scope'].downcase %>)
34
+ expect do
35
+ delete "/<%= options['scope'].downcase.pluralize %>/#{<%= options['scope'].downcase %>.id}/<%=plural_name %>/#{<%= singular_name %>.id}"
36
+ end.to change(<%= class_name %>, :count).by(-1)
37
+ end
38
+ end
39
+
40
+ describe "GET/ <%= singular_name %>" do
41
+ let(:<%= options['scope'].downcase %>) {create(:<%= options['scope'].downcase %>)}
42
+ let(:<%= singular_table_name %>) { create(:<%=singular_table_name %>, <%= options['scope'].downcase %>: <%= options['scope'].downcase %>)}
43
+
44
+ it "gets an <%=singular_name %>" do
45
+ get "/<%= options['scope'].downcase.pluralize %>/#{<%= options['scope'].downcase %>.id}/<%= plural_name %>/#{<%= singular_name %>.id}"
46
+ expect(response).to be_successful
47
+ end
48
+ end
49
+
50
+ describe "GET /<%= plural_name %>" do
51
+ let(:<%= options['scope'].downcase %>) {create(:<%= options['scope'].downcase %>)}
52
+ let(:<%= singular_table_name %>) { create(:<%=singular_table_name %>, <%= options['scope'].downcase %>: <%= options['scope'].downcase %>) }
53
+
54
+ it "renders a successful response" do
55
+ get "/<%= options['scope'].downcase.pluralize %>/#{<%= options['scope'].downcase %>.id}/<%= plural_name %>"
56
+ expect(response).to be_successful
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,36 @@
1
+ class <%= class_name.pluralize %>Controller < ApplicationController
2
+ before_action :set_<%= singular_name %>, only: %i[ show update destroy ]
3
+
4
+ def index
5
+ @<%= singular_name %> = <%= class_name %>.all
6
+ render json: @<%= singular_name %>, status: :ok
7
+ end
8
+
9
+ def show
10
+ render json: @<%= singular_name %>, status: :ok
11
+ end
12
+
13
+ def create
14
+ @<%= singular_name %> = <%= class_name %>.create!(<%= singular_name %>_params)
15
+ render json: @<%= singular_name %>, status: :created
16
+ end
17
+
18
+ def update
19
+ @<%= singular_name %> = <%= class_name %>.update!(<%= singular_name %>_params)
20
+ render json: @<%= singular_name %>, status: :ok
21
+ end
22
+
23
+ def destroy
24
+ @<%= singular_name %>.destroy!
25
+ end
26
+
27
+ private
28
+
29
+ def set_<%= singular_name %>
30
+ @<%= singular_name %> = <%= class_name %>.find(params[:id])
31
+ end
32
+
33
+ def <%= singular_name %>_params
34
+ params.require(:<%= singular_name %>).permit(<%= attributes.map { |a| ':' + a.name }.join(', ') %>)
35
+ end
36
+ end
@@ -0,0 +1,47 @@
1
+ require 'rails_helper'
2
+
3
+ RSpec.describe "<%= class_name %>", type: :request do
4
+ let(:<%= singular_table_name %>) { create(:<%= singular_table_name %>) }
5
+ let(:valid_attributes) { attributes_for(:<%= singular_table_name %>) }
6
+
7
+ describe "GET /<%= plural_name %>" do
8
+ it "returns http success" do
9
+ create(:<%= singular_table_name %>)
10
+ get "/<%= plural_name %>"
11
+ expect(response).to have_http_status(:success)
12
+ end
13
+ end
14
+
15
+ describe "GET /<%= plural_name %>/:id" do
16
+ it "returns http success" do
17
+ get "/<%= plural_name %>/#{<%= singular_name %>.id}"
18
+ expect(response).to have_http_status(:success)
19
+ end
20
+ end
21
+
22
+ describe "POST /<%= plural_name %>" do
23
+ it "creates a new item" do
24
+ expect do
25
+ post "/<%= plural_name %>",
26
+ params: { <%= singular_name %>: valid_attributes }
27
+ end.to change(<%= class_name %>, :count).by(1)
28
+ end
29
+ end
30
+
31
+ describe "PATCH /<%= plural_name %>/:id" do
32
+ it "return http success" do
33
+ patch "/<%= plural_name %>/#{<%= singular_name %>.id}",
34
+ params: { <%= singular_name %>: valid_attributes }
35
+ expect(response).to have_http_status(:success)
36
+ end
37
+ end
38
+
39
+ describe "DELETE /<%= plural_name %>/:id" do
40
+ it "deletes an <%= plural_name %>" do
41
+ item = create(:<%= singular_name %>)
42
+ expect do
43
+ delete "/<%= plural_name %>/#{item.id}"
44
+ end.to change(<%= class_name %>, :count).by(-1)
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RestApiGenerator
4
+ class CustomError < StandardError
5
+ attr_reader :status, :error, :message
6
+
7
+ def initialize(error: 422, status: :unprocessable_entity, message: "Something went wrong")
8
+ @error = error
9
+ @status = status
10
+ @message = message
11
+ super(msg: message)
12
+ end
13
+
14
+ def fetch_json
15
+ Helpers::Render.json(error, message, status)
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RestApiGenerator
4
+ module ErrorHandler
5
+ def self.included(clazz)
6
+ clazz.class_eval do
7
+ rescue_from ActiveRecord::RecordNotFound do |e|
8
+ respond(:record_not_found, 404, e.to_s)
9
+ end
10
+ rescue_from ActiveRecord::ActiveRecordError do |e|
11
+ respond(:active_record_error, 422, e.to_s)
12
+ end
13
+ rescue_from ActiveRecord::RecordInvalid do |e|
14
+ respond(:active_record_invalid, 422, e.to_s)
15
+ end
16
+ rescue_from ActiveModel::ValidationError do |e|
17
+ respond(:active_model_validation_error, 422, e.to_s)
18
+ end
19
+ rescue_from CustomError do |e|
20
+ respond(e.error, e.status, e.message)
21
+ end
22
+ end
23
+ end
24
+
25
+ private
26
+
27
+ def respond(error, status, message)
28
+ json = Helpers::Render.json(error, status, message)
29
+ render json: json, status: status
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RestApiGenerator
4
+ module Helpers
5
+ class Render
6
+ def self.json(error, status, message)
7
+ {
8
+ status: status,
9
+ error: error,
10
+ message: message
11
+ }.as_json
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RestApiGenerator
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "rest_api_generator/version"
4
+ require_relative "rest_api_generator/error_handler"
5
+ require_relative "rest_api_generator/custom_error"
6
+ require_relative "rest_api_generator/helpers/render"
7
+
8
+ module RestApiGenerator
9
+ class Error < StandardError; end
10
+ # Your code goes here...
11
+ end
@@ -0,0 +1,4 @@
1
+ module RestApiGenerator
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,85 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rest-api-generator
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - PedroAugustoRamalhoDuarte
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-10-05 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: railties
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: 5.0.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: 5.0.0
27
+ description: Generates rest api in SwitchDreams default faster with rest-api-generator
28
+ email:
29
+ - pedro_aduarte@aluno.unb.br
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".rspec"
35
+ - ".rubocop.yml"
36
+ - CODE_OF_CONDUCT.md
37
+ - Gemfile
38
+ - Gemfile.lock
39
+ - LICENSE.txt
40
+ - README.md
41
+ - Rakefile
42
+ - bin/console
43
+ - bin/setup
44
+ - lib/generators/rest_api_generator/USAGE
45
+ - lib/generators/rest_api_generator/helpers.rb
46
+ - lib/generators/rest_api_generator/resource_generator.rb
47
+ - lib/generators/rest_api_generator/templates/child_api_controller.rb.tt
48
+ - lib/generators/rest_api_generator/templates/child_api_spec.rb.tt
49
+ - lib/generators/rest_api_generator/templates/rest_api_controller.rb.tt
50
+ - lib/generators/rest_api_generator/templates/rest_api_spec.rb.tt
51
+ - lib/rest_api_generator.rb
52
+ - lib/rest_api_generator/custom_error.rb
53
+ - lib/rest_api_generator/error_handler.rb
54
+ - lib/rest_api_generator/helpers/render.rb
55
+ - lib/rest_api_generator/version.rb
56
+ - sig/rest_api_generator.rbs
57
+ homepage: https://github.com/SwitchDreams/rest-api-generator
58
+ licenses:
59
+ - MIT
60
+ metadata:
61
+ allowed_push_host: https://rubygems.org/
62
+ homepage_uri: https://github.com/SwitchDreams/rest-api-generator
63
+ source_code_uri: https://github.com/SwitchDreams/rest-api-generator
64
+ changelog_uri: https://github.com/SwitchDreams/rest-api-generator
65
+ rubygems_mfa_required: 'true'
66
+ post_install_message:
67
+ rdoc_options: []
68
+ require_paths:
69
+ - lib
70
+ required_ruby_version: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: 2.6.0
75
+ required_rubygems_version: !ruby/object:Gem::Requirement
76
+ requirements:
77
+ - - ">="
78
+ - !ruby/object:Gem::Version
79
+ version: '0'
80
+ requirements: []
81
+ rubygems_version: 3.3.7
82
+ signing_key:
83
+ specification_version: 4
84
+ summary: Build a rails rest api in minutes
85
+ test_files: []