├── .circleci ├── config.yml └── setup-rubygems.sh ├── .coveralls.yml ├── .gitignore ├── .rspec ├── .rubocop.yml ├── .ruby-version ├── CHANGELOG.md ├── Gemfile ├── Gemfile.lock ├── Guardfile ├── LICENSE.txt ├── README.md ├── Rakefile ├── app ├── assets │ ├── config │ │ └── power_api_manifest.js │ ├── images │ │ └── power_api │ │ │ └── .keep │ ├── javascripts │ │ └── power_api │ │ │ └── application.js │ └── stylesheets │ │ └── power_api │ │ └── application.css ├── controllers │ ├── concerns │ │ └── api │ │ │ ├── deprecated.rb │ │ │ ├── error.rb │ │ │ └── filtered.rb │ └── power_api │ │ └── base_controller.rb ├── helpers │ └── power_api │ │ └── application_helper.rb ├── jobs │ └── power_api │ │ └── application_job.rb ├── mailers │ └── power_api │ │ └── application_mailer.rb ├── models │ └── power_api │ │ └── application_record.rb ├── responders │ └── api_responder.rb └── views │ └── layouts │ └── power_api │ └── application.html.erb ├── bin ├── clean_test_app └── rails ├── config └── routes.rb ├── lib ├── generators │ └── power_api │ │ ├── controller │ │ ├── USAGE │ │ └── controller_generator.rb │ │ ├── exposed_api_config │ │ ├── USAGE │ │ └── exposed_api_config_generator.rb │ │ ├── install │ │ ├── USAGE │ │ └── install_generator.rb │ │ ├── internal_api_config │ │ ├── USAGE │ │ └── internal_api_config_generator.rb │ │ └── version │ │ ├── USAGE │ │ └── version_generator.rb ├── power_api.rb ├── power_api │ ├── engine.rb │ ├── errors.rb │ ├── generator_helper │ │ ├── active_record_resource.rb │ │ ├── ams_helper.rb │ │ ├── api_helper.rb │ │ ├── controller_actions_helper.rb │ │ ├── controller_helper.rb │ │ ├── pagination_helper.rb │ │ ├── resource_helper.rb │ │ ├── routes_helper.rb │ │ ├── rspec_controller_helper.rb │ │ ├── rubocop_helper.rb │ │ ├── simple_token_auth_helper.rb │ │ └── template_builder_helper.rb │ ├── generator_helpers.rb │ └── version.rb └── tasks │ └── power_api_tasks.rake ├── power_api.gemspec └── spec ├── dummy ├── Rakefile ├── app │ ├── assets │ │ ├── config │ │ │ └── manifest.js │ │ ├── images │ │ │ └── .keep │ │ └── stylesheets │ │ │ └── application.css │ ├── channels │ │ └── application_cable │ │ │ ├── channel.rb │ │ │ └── connection.rb │ ├── controllers │ │ ├── api │ │ │ ├── base_controller.rb │ │ │ └── internal │ │ │ │ ├── base_controller.rb │ │ │ │ └── blogs_controller.rb │ │ ├── application_controller.rb │ │ └── concerns │ │ │ ├── .keep │ │ │ └── api │ │ │ ├── deprecated_spec.rb │ │ │ ├── error_spec.rb │ │ │ └── filtered_spec.rb │ ├── helpers │ │ └── application_helper.rb │ ├── javascript │ │ └── packs │ │ │ └── application.js │ ├── jobs │ │ └── application_job.rb │ ├── mailers │ │ └── application_mailer.rb │ ├── models │ │ ├── application_record.rb │ │ ├── blog.rb │ │ ├── concerns │ │ │ └── .keep │ │ ├── portfolio.rb │ │ └── user.rb │ ├── serializers │ │ └── api │ │ │ └── internal │ │ │ └── blog_serializer.rb │ └── views │ │ └── layouts │ │ ├── application.html.erb │ │ ├── mailer.html.erb │ │ └── mailer.text.erb ├── bin │ ├── rails │ ├── rake │ └── setup ├── config.ru ├── config │ ├── application.rb │ ├── boot.rb │ ├── cable.yml │ ├── database.yml │ ├── environment.rb │ ├── environments │ │ ├── development.rb │ │ ├── production.rb │ │ └── test.rb │ ├── initializers │ │ ├── active_model_serializers.rb │ │ ├── api_pagination.rb │ │ ├── application_controller_renderer.rb │ │ ├── assets.rb │ │ ├── backtrace_silencers.rb │ │ ├── content_security_policy.rb │ │ ├── cookies_serializer.rb │ │ ├── filter_parameter_logging.rb │ │ ├── inflections.rb │ │ ├── mime_types.rb │ │ ├── permissions_policy.rb │ │ └── wrap_parameters.rb │ ├── locales │ │ └── en.yml │ ├── puma.rb │ ├── routes.rb │ └── storage.yml ├── db │ ├── migrate │ │ ├── 20190322205209_create_blogs.rb │ │ ├── 20200215225917_create_users.rb │ │ ├── 20200227150449_create_portfolios.rb │ │ └── 20200227150548_add_portfolio_id_blogs.rb │ └── schema.rb ├── lib │ └── assets │ │ └── .keep ├── log │ └── .keep ├── package.json ├── public │ ├── 404.html │ ├── 422.html │ ├── 500.html │ ├── apple-touch-icon-precomposed.png │ ├── apple-touch-icon.png │ └── favicon.ico ├── spec │ ├── assets │ │ ├── image.png │ │ └── video.mp4 │ ├── factories │ │ ├── blogs.rb │ │ ├── portfolios.rb │ │ └── users.rb │ ├── helpers │ │ └── power_api │ │ │ └── application_helper_spec.rb │ ├── lib │ │ └── power_api │ │ │ └── generator_helper │ │ │ ├── ams_helper_spec.rb │ │ │ ├── api_helper_spec.rb │ │ │ ├── controller_actions_helper_spec.rb │ │ │ ├── controller_helper_spec.rb │ │ │ ├── pagination_helper_spec.rb │ │ │ ├── resource_helper_spec.rb │ │ │ ├── routes_helper_spec.rb │ │ │ ├── rspec_controller_helper_spec.rb │ │ │ └── simple_token_auth_helper_spec.rb │ └── support │ │ ├── shared_examples │ │ ├── active_record_resource.rb │ │ └── active_record_resource_atrributes.rb │ │ ├── test_generator_helpers.rb │ │ └── test_helpers.rb └── storage │ └── .keep ├── rails_helper.rb └── spec_helper.rb /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | env-vars: &env-vars 4 | RAILS_ENV: test 5 | NODE_ENV: test 6 | BUNDLE_PATH: vendor/bundle 7 | 8 | orbs: 9 | ruby: circleci/ruby@0.1.2 10 | browser-tools: circleci/browser-tools@1.1.3 11 | 12 | executors: 13 | main-executor: 14 | parameters: 15 | ruby-version: 16 | description: "Ruby version" 17 | default: "2.7" 18 | type: string 19 | docker: 20 | - image: circleci/ruby:<>-node 21 | environment: *env-vars 22 | 23 | commands: 24 | setup: 25 | description: checkout code and install dependencies 26 | steps: 27 | - checkout 28 | - run: 29 | name: Install bundle dependencies 30 | command: | 31 | BUNDLER_VERSION=$(cat Gemfile.lock | tail -1 | tr -d " ") 32 | gem install bundler:$BUNDLER_VERSION 33 | bundle _$(echo $BUNDLER_VERSION)_ install 34 | 35 | jobs: 36 | lint: 37 | executor: main-executor 38 | steps: 39 | - setup 40 | - run: 41 | name: Install reviewdog 42 | command: | 43 | curl -sfL https://raw.githubusercontent.com/reviewdog/reviewdog/master/install.sh | sh -s -- -b ./bin 44 | - run: 45 | name: Get files to lint 46 | command: | 47 | mkdir tmp 48 | git diff origin/master --name-only --diff-filter=d > tmp/files_to_lint 49 | - run: 50 | name: Run rubocop 51 | shell: /bin/bash 52 | command: | 53 | cat tmp/files_to_lint | grep -E '.+\.(rb)$' | xargs bundle exec rubocop --force-exclusion \ 54 | | ./bin/reviewdog -reporter=github-pr-review -f=rubocop 55 | test: 56 | parameters: 57 | ruby-version: 58 | description: "Ruby version" 59 | default: "2.7" 60 | type: string 61 | executor: 62 | name: main-executor 63 | ruby-version: <> 64 | steps: 65 | - setup 66 | - run: 67 | name: Run Tests 68 | command: | 69 | RSPEC_JUNIT_ARGS="-r rspec_junit_formatter -f RspecJunitFormatter -o test_results/rspec.xml" 70 | RSPEC_FORMAT_ARGS="-f progress --no-color -p 10" 71 | bundle exec rspec ./spec $RSPEC_FORMAT_ARGS $RSPEC_JUNIT_ARGS 72 | - store_test_results: 73 | path: test_results 74 | deploy: 75 | executor: main-executor 76 | steps: 77 | - setup 78 | - run: 79 | name: Setup rubygems 80 | command: bash .circleci/setup-rubygems.sh 81 | - run: 82 | name: Publish to rubygems 83 | command: | 84 | gem build power_api.gemspec 85 | version_tag=$(git describe --tags) 86 | gem push power_api-${version_tag#v}.gem 87 | 88 | workflows: 89 | version: 2 90 | main: 91 | jobs: 92 | - lint: 93 | context: org-global 94 | - test: 95 | matrix: 96 | parameters: 97 | ruby-version: ["2.7"] 98 | - deploy: 99 | context: org-global 100 | filters: 101 | tags: 102 | only: /.*/ 103 | branches: 104 | ignore: /.*/ 105 | -------------------------------------------------------------------------------- /.circleci/setup-rubygems.sh: -------------------------------------------------------------------------------- 1 | mkdir ~/.gem 2 | echo -e "---\r\n:rubygems_api_key: $RUBYGEMS_API_KEY" > ~/.gem/credentials 3 | chmod 0600 /home/circleci/.gem/credentials 4 | -------------------------------------------------------------------------------- /.coveralls.yml: -------------------------------------------------------------------------------- 1 | service_name: travis-ci 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .bundle/ 2 | log/*.log 3 | pkg/ 4 | spec/dummy/db/*.sqlite3 5 | spec/dummy/db/*.sqlite3-journal 6 | spec/dummy/log/*.log 7 | spec/dummy/tmp/ 8 | spec/dummy/.sass-cache 9 | coverage/ 10 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --color 2 | --require rails_helper 3 | --format=doc 4 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | 2.7 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | All notable changes to this project will be documented in this file. 3 | This project adheres to [Semantic Versioning](http://semver.org/). 4 | 5 | ### v2.1.1 6 | 7 | * Fix: add `nil` handling in the `serialize_resource` view helper. 8 | 9 | ### v2.1.0 10 | 11 | * Swagger has been deleted from the Exposed Api version. 12 | 13 | ### v2.0.2 14 | 15 | * Fix: change the way PowerApi::ApplicationHelper is loaded into host app. 16 | 17 | ### v2.0.1 18 | 19 | * Fix: trying to reference ApplicationController in wrong namespace. 20 | ### v2.0.0 21 | 22 | * Add API internal and exposed modes. 23 | * Replace `json_api` with `json` adapter. 24 | * Add view helper to serialize resources. 25 | 26 | ### v1.0.0 27 | 28 | * Replace travis with circleci. 29 | * Use Rails 6 on Dummy app. 30 | 31 | ### v0.2.0 32 | 33 | * Add `controller-actions` option to generator 34 | ### v0.1.0 35 | 36 | * Initial release. 37 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | # Declare your gem's dependencies in power_api.gemspec. 4 | # Bundler will treat runtime dependencies like base dependencies, and 5 | # development dependencies will be added by default to the :development group. 6 | gemspec 7 | 8 | # Declare any dependencies that are still in development here instead of in 9 | # your gemspec. These might include edge Rails or gems from your path or 10 | # Git. Remember to move these dependencies to your gemspec before releasing 11 | # your gem to rubygems.org. 12 | 13 | # To use a debugger 14 | # gem 'byebug', group: [:development, :test] 15 | 16 | gem "api-pagination", "~> 4.8.2" -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | PATH 2 | remote: . 3 | specs: 4 | power_api (2.1.1) 5 | active_model_serializers (~> 0.10.0) 6 | api-pagination 7 | kaminari 8 | rails (>= 6.0) 9 | ransack 10 | responders 11 | simple_token_authentication (~> 1.0) 12 | versionist (~> 1.0) 13 | 14 | GEM 15 | remote: https://rubygems.org/ 16 | specs: 17 | actioncable (6.1.6) 18 | actionpack (= 6.1.6) 19 | activesupport (= 6.1.6) 20 | nio4r (~> 2.0) 21 | websocket-driver (>= 0.6.1) 22 | actionmailbox (6.1.6) 23 | actionpack (= 6.1.6) 24 | activejob (= 6.1.6) 25 | activerecord (= 6.1.6) 26 | activestorage (= 6.1.6) 27 | activesupport (= 6.1.6) 28 | mail (>= 2.7.1) 29 | actionmailer (6.1.6) 30 | actionpack (= 6.1.6) 31 | actionview (= 6.1.6) 32 | activejob (= 6.1.6) 33 | activesupport (= 6.1.6) 34 | mail (~> 2.5, >= 2.5.4) 35 | rails-dom-testing (~> 2.0) 36 | actionpack (6.1.6) 37 | actionview (= 6.1.6) 38 | activesupport (= 6.1.6) 39 | rack (~> 2.0, >= 2.0.9) 40 | rack-test (>= 0.6.3) 41 | rails-dom-testing (~> 2.0) 42 | rails-html-sanitizer (~> 1.0, >= 1.2.0) 43 | actiontext (6.1.6) 44 | actionpack (= 6.1.6) 45 | activerecord (= 6.1.6) 46 | activestorage (= 6.1.6) 47 | activesupport (= 6.1.6) 48 | nokogiri (>= 1.8.5) 49 | actionview (6.1.6) 50 | activesupport (= 6.1.6) 51 | builder (~> 3.1) 52 | erubi (~> 1.4) 53 | rails-dom-testing (~> 2.0) 54 | rails-html-sanitizer (~> 1.1, >= 1.2.0) 55 | active_model_serializers (0.10.13) 56 | actionpack (>= 4.1, < 7.1) 57 | activemodel (>= 4.1, < 7.1) 58 | case_transform (>= 0.2) 59 | jsonapi-renderer (>= 0.1.1.beta1, < 0.3) 60 | activejob (6.1.6) 61 | activesupport (= 6.1.6) 62 | globalid (>= 0.3.6) 63 | activemodel (6.1.6) 64 | activesupport (= 6.1.6) 65 | activerecord (6.1.6) 66 | activemodel (= 6.1.6) 67 | activesupport (= 6.1.6) 68 | activestorage (6.1.6) 69 | actionpack (= 6.1.6) 70 | activejob (= 6.1.6) 71 | activerecord (= 6.1.6) 72 | activesupport (= 6.1.6) 73 | marcel (~> 1.0) 74 | mini_mime (>= 1.1.0) 75 | activesupport (6.1.6) 76 | concurrent-ruby (~> 1.0, >= 1.0.2) 77 | i18n (>= 1.6, < 2) 78 | minitest (>= 5.1) 79 | tzinfo (~> 2.0) 80 | zeitwerk (~> 2.3) 81 | api-pagination (4.8.2) 82 | ast (2.4.2) 83 | bcrypt (3.1.18) 84 | builder (3.2.4) 85 | case_transform (0.2) 86 | activesupport 87 | coderay (1.1.3) 88 | concurrent-ruby (1.1.10) 89 | coveralls (0.8.23) 90 | json (>= 1.8, < 3) 91 | simplecov (~> 0.16.1) 92 | term-ansicolor (~> 1.3) 93 | thor (>= 0.19.4, < 2.0) 94 | tins (~> 1.6) 95 | crass (1.0.6) 96 | devise (4.8.1) 97 | bcrypt (~> 3.0) 98 | orm_adapter (~> 0.1) 99 | railties (>= 4.1.0) 100 | responders 101 | warden (~> 1.2.3) 102 | diff-lcs (1.4.4) 103 | docile (1.4.0) 104 | erubi (1.10.0) 105 | factory_bot (6.2.0) 106 | activesupport (>= 5.0.0) 107 | factory_bot_rails (6.2.0) 108 | factory_bot (~> 6.2.0) 109 | railties (>= 5.0.0) 110 | ffi (1.15.3) 111 | formatador (0.3.0) 112 | globalid (1.0.0) 113 | activesupport (>= 5.0) 114 | guard (2.17.0) 115 | formatador (>= 0.2.4) 116 | listen (>= 2.7, < 4.0) 117 | lumberjack (>= 1.0.12, < 2.0) 118 | nenv (~> 0.1) 119 | notiffany (~> 0.0) 120 | pry (>= 0.9.12) 121 | shellany (~> 0.0) 122 | thor (>= 0.18.1) 123 | guard-compat (1.2.1) 124 | guard-rspec (4.7.3) 125 | guard (~> 2.1) 126 | guard-compat (~> 1.1) 127 | rspec (>= 2.99.0, < 4.0) 128 | i18n (1.10.0) 129 | concurrent-ruby (~> 1.0) 130 | jaro_winkler (1.5.4) 131 | json (2.5.1) 132 | jsonapi-renderer (0.2.2) 133 | kaminari (1.2.2) 134 | activesupport (>= 4.1.0) 135 | kaminari-actionview (= 1.2.2) 136 | kaminari-activerecord (= 1.2.2) 137 | kaminari-core (= 1.2.2) 138 | kaminari-actionview (1.2.2) 139 | actionview 140 | kaminari-core (= 1.2.2) 141 | kaminari-activerecord (1.2.2) 142 | activerecord 143 | kaminari-core (= 1.2.2) 144 | kaminari-core (1.2.2) 145 | listen (3.5.1) 146 | rb-fsevent (~> 0.10, >= 0.10.3) 147 | rb-inotify (~> 0.9, >= 0.9.10) 148 | loofah (2.18.0) 149 | crass (~> 1.0.2) 150 | nokogiri (>= 1.5.9) 151 | lumberjack (1.2.8) 152 | mail (2.7.1) 153 | mini_mime (>= 0.1.1) 154 | marcel (1.0.2) 155 | method_source (1.0.0) 156 | mini_mime (1.1.2) 157 | minitest (5.15.0) 158 | nenv (0.3.0) 159 | nio4r (2.5.8) 160 | nokogiri (1.13.6-arm64-darwin) 161 | racc (~> 1.4) 162 | nokogiri (1.13.6-x86_64-darwin) 163 | racc (~> 1.4) 164 | nokogiri (1.13.6-x86_64-linux) 165 | racc (~> 1.4) 166 | notiffany (0.1.3) 167 | nenv (~> 0.1) 168 | shellany (~> 0.0) 169 | orm_adapter (0.5.0) 170 | parallel (1.20.1) 171 | parser (3.0.1.1) 172 | ast (~> 2.4.1) 173 | powerpack (0.1.3) 174 | pry (0.14.1) 175 | coderay (~> 1.1) 176 | method_source (~> 1.0) 177 | pry-rails (0.3.9) 178 | pry (>= 0.10.4) 179 | psych (4.0.1) 180 | racc (1.6.0) 181 | rack (2.2.3) 182 | rack-test (1.1.0) 183 | rack (>= 1.0, < 3) 184 | rails (6.1.6) 185 | actioncable (= 6.1.6) 186 | actionmailbox (= 6.1.6) 187 | actionmailer (= 6.1.6) 188 | actionpack (= 6.1.6) 189 | actiontext (= 6.1.6) 190 | actionview (= 6.1.6) 191 | activejob (= 6.1.6) 192 | activemodel (= 6.1.6) 193 | activerecord (= 6.1.6) 194 | activestorage (= 6.1.6) 195 | activesupport (= 6.1.6) 196 | bundler (>= 1.15.0) 197 | railties (= 6.1.6) 198 | sprockets-rails (>= 2.0.0) 199 | rails-dom-testing (2.0.3) 200 | activesupport (>= 4.2.0) 201 | nokogiri (>= 1.6) 202 | rails-html-sanitizer (1.4.2) 203 | loofah (~> 2.3) 204 | railties (6.1.6) 205 | actionpack (= 6.1.6) 206 | activesupport (= 6.1.6) 207 | method_source 208 | rake (>= 12.2) 209 | thor (~> 1.0) 210 | rainbow (3.0.0) 211 | rake (13.0.6) 212 | ransack (3.2.0) 213 | activerecord (>= 6.1.5) 214 | activesupport (>= 6.1.5) 215 | i18n 216 | rb-fsevent (0.11.0) 217 | rb-inotify (0.10.1) 218 | ffi (~> 1.0) 219 | responders (3.0.1) 220 | actionpack (>= 5.0) 221 | railties (>= 5.0) 222 | rspec (3.10.0) 223 | rspec-core (~> 3.10.0) 224 | rspec-expectations (~> 3.10.0) 225 | rspec-mocks (~> 3.10.0) 226 | rspec-core (3.10.1) 227 | rspec-support (~> 3.10.0) 228 | rspec-expectations (3.10.1) 229 | diff-lcs (>= 1.2.0, < 2.0) 230 | rspec-support (~> 3.10.0) 231 | rspec-mocks (3.10.2) 232 | diff-lcs (>= 1.2.0, < 2.0) 233 | rspec-support (~> 3.10.0) 234 | rspec-rails (5.0.1) 235 | actionpack (>= 5.2) 236 | activesupport (>= 5.2) 237 | railties (>= 5.2) 238 | rspec-core (~> 3.10) 239 | rspec-expectations (~> 3.10) 240 | rspec-mocks (~> 3.10) 241 | rspec-support (~> 3.10) 242 | rspec-support (3.10.2) 243 | rspec_junit_formatter (0.4.1) 244 | rspec-core (>= 2, < 4, != 2.12.0) 245 | rubocop (0.65.0) 246 | jaro_winkler (~> 1.5.1) 247 | parallel (~> 1.10) 248 | parser (>= 2.5, != 2.5.1.1) 249 | powerpack (~> 0.1) 250 | psych (>= 3.1.0) 251 | rainbow (>= 2.2.2, < 4.0) 252 | ruby-progressbar (~> 1.7) 253 | unicode-display_width (~> 1.4.0) 254 | rubocop-rspec (1.35.0) 255 | rubocop (>= 0.60.0) 256 | ruby-progressbar (1.11.0) 257 | shellany (0.0.1) 258 | simple_token_authentication (1.17.0) 259 | actionmailer (>= 3.2.6, < 7) 260 | actionpack (>= 3.2.6, < 7) 261 | devise (>= 3.2, < 6) 262 | simplecov (0.16.1) 263 | docile (~> 1.1) 264 | json (>= 1.8, < 3) 265 | simplecov-html (~> 0.10.0) 266 | simplecov-html (0.10.2) 267 | sprockets (4.0.3) 268 | concurrent-ruby (~> 1.0) 269 | rack (> 1, < 3) 270 | sprockets-rails (3.4.2) 271 | actionpack (>= 5.2) 272 | activesupport (>= 5.2) 273 | sprockets (>= 3.0.0) 274 | sqlite3 (1.4.2) 275 | sync (0.5.0) 276 | term-ansicolor (1.7.1) 277 | tins (~> 1.0) 278 | thor (1.2.1) 279 | tins (1.29.1) 280 | sync 281 | tzinfo (2.0.4) 282 | concurrent-ruby (~> 1.0) 283 | unicode-display_width (1.4.1) 284 | versionist (1.7.0) 285 | activesupport (>= 3) 286 | railties (>= 3) 287 | yard (~> 0.9.11) 288 | warden (1.2.9) 289 | rack (>= 2.0.9) 290 | webrick (1.7.0) 291 | websocket-driver (0.7.5) 292 | websocket-extensions (>= 0.1.0) 293 | websocket-extensions (0.1.5) 294 | yard (0.9.27) 295 | webrick (~> 1.7.0) 296 | zeitwerk (2.5.4) 297 | 298 | PLATFORMS 299 | arm64-darwin-20 300 | x86_64-darwin-20 301 | x86_64-linux 302 | 303 | DEPENDENCIES 304 | api-pagination (~> 4.8.2) 305 | coveralls 306 | factory_bot_rails 307 | guard-rspec 308 | power_api! 309 | pry 310 | pry-rails 311 | rspec-rails 312 | rspec_junit_formatter 313 | rubocop (= 0.65.0) 314 | rubocop-rspec 315 | sqlite3 (~> 1.4.2) 316 | 317 | BUNDLED WITH 318 | 2.4.10 319 | -------------------------------------------------------------------------------- /Guardfile: -------------------------------------------------------------------------------- 1 | guard :rspec, cmd: "bundle exec rspec" do 2 | spec_dic = "spec/dummy/spec" 3 | # RSpec files 4 | watch("spec/spec_helper.rb") { spec_dic } 5 | watch("spec/rails_helper.rb") { spec_dic } 6 | watch(%r{^spec\/dummy\/spec\/support\/(.+)\.rb$}) { spec_dic } 7 | watch(%r{^spec\/dummy\/spec\/.+_spec\.rb$}) 8 | # Engine files 9 | watch(%r{^lib/(.+)\.rb$}) { |m| "spec/dummy/spec/lib/#{m[1]}_spec.rb" } 10 | watch(%r{^app/(.+)\.rb$}) { |m| "spec/dummy/spec/#{m[1]}_spec.rb" } 11 | watch(%r{^app/(.*)(\.erb)$}) { |m| "spec/dummy/spec/#{m[1]}#{m[2]}_spec.rb" } 12 | # Dummy app files 13 | watch(%r{^spec\/dummy\/app/(.+)\.rb$}) { |m| "spec/dummy/spec/#{m[1]}_spec.rb" } 14 | watch(%r{^spec\/dummy\/app/(.*)(\.erb)$}) { |m| "spec/dummy/spec/#{m[1]}#{m[2]}_spec.rb" } 15 | end 16 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright 2019 Platanus 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. 22 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | begin 2 | require "bundler/setup" 3 | rescue LoadError 4 | puts "You must `gem install bundler` and `bundle install` to run rake tasks" 5 | end 6 | 7 | APP_RAKEFILE = File.expand_path("../spec/dummy/Rakefile", __FILE__) 8 | load "rails/tasks/engine.rake" 9 | load "rails/tasks/statistics.rake" 10 | Bundler::GemHelper.install_tasks 11 | -------------------------------------------------------------------------------- /app/assets/config/power_api_manifest.js: -------------------------------------------------------------------------------- 1 | //= link_directory ../javascripts/power_api .js 2 | //= link_directory ../stylesheets/power_api .css 3 | -------------------------------------------------------------------------------- /app/assets/images/power_api/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/platanus/power_api/fc84727c8772199266af4d66f88b2bdd6dd0c4f4/app/assets/images/power_api/.keep -------------------------------------------------------------------------------- /app/assets/javascripts/power_api/application.js: -------------------------------------------------------------------------------- 1 | // This is a manifest file that'll be compiled into application.js, which will include all the files 2 | // listed below. 3 | // 4 | // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, 5 | // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. 6 | // 7 | // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the 8 | // compiled file. JavaScript code in this file should be added after the last require_* statement. 9 | // 10 | // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details 11 | // about supported directives. 12 | // 13 | //= require_tree . 14 | -------------------------------------------------------------------------------- /app/assets/stylesheets/power_api/application.css: -------------------------------------------------------------------------------- 1 | /* 2 | * This is a manifest file that'll be compiled into application.css, which will include all the files 3 | * listed below. 4 | * 5 | * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, 6 | * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path. 7 | * 8 | * You're free to add application-wide styles to this file and they'll appear at the bottom of the 9 | * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS 10 | * files in this directory. Styles in this file should be added after the last require_* statement. 11 | * It is generally better to create a new file per style scope. 12 | * 13 | *= require_tree . 14 | *= require_self 15 | */ 16 | -------------------------------------------------------------------------------- /app/controllers/concerns/api/deprecated.rb: -------------------------------------------------------------------------------- 1 | module Api::Deprecated 2 | extend ActiveSupport::Concern 3 | 4 | class_methods do 5 | attr_accessor :deprecated_actions 6 | 7 | def deprecate(*actions) 8 | self.deprecated_actions ||= {} 9 | self.deprecated_actions[to_s] = actions 10 | end 11 | end 12 | 13 | included do 14 | after_action :deprecate_actions 15 | 16 | def deprecate_actions 17 | return unless self.class.deprecated_actions 18 | 19 | deprecated_actions = self.class.deprecated_actions[self.class.to_s] 20 | response.headers["Deprecated"] = true if deprecated_actions.include?(params[:action].to_sym) 21 | end 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /app/controllers/concerns/api/error.rb: -------------------------------------------------------------------------------- 1 | module Api::Error 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | rescue_from "Exception" do |exception| 6 | logger.error exception.message 7 | logger.error exception.backtrace.join("\n") 8 | respond_api_error(:internal_server_error, message: "server_error", 9 | type: exception.class.to_s, 10 | detail: exception.message) 11 | end 12 | 13 | rescue_from "ActiveRecord::RecordNotFound" do |exception| 14 | respond_api_error(:not_found, message: "record_not_found", 15 | detail: exception.message) 16 | end 17 | 18 | rescue_from "ActiveModel::ForbiddenAttributesError" do |exception| 19 | respond_api_error(:bad_request, message: "protected_attributes", 20 | detail: exception.message) 21 | end 22 | 23 | rescue_from "ActiveRecord::RecordInvalid" do |exception| 24 | respond_api_error(:bad_request, message: "invalid_attributes", 25 | errors: exception.record.errors) 26 | end 27 | 28 | rescue_from "PowerApi::InvalidVersion" do |exception| 29 | respond_api_error(:bad_request, message: "invalid_api_version", 30 | errors: exception.message) 31 | end 32 | end 33 | 34 | def respond_api_error(status, error = {}) 35 | render json: error, status: status 36 | end 37 | end 38 | -------------------------------------------------------------------------------- /app/controllers/concerns/api/filtered.rb: -------------------------------------------------------------------------------- 1 | module Api::Filtered 2 | extend ActiveSupport::Concern 3 | 4 | def filtered_collection(collection) 5 | collection.ransack(query_string_filters).result 6 | end 7 | 8 | private 9 | 10 | def query_string_filters 11 | return {} if params[:q].blank? 12 | 13 | params[:q]&.to_unsafe_h || {} 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /app/controllers/power_api/base_controller.rb: -------------------------------------------------------------------------------- 1 | module PowerApi 2 | class BaseController < ApplicationController 3 | include Rails::Pagination 4 | 5 | include Api::Error 6 | include Api::Deprecated 7 | include Api::Filtered 8 | 9 | self.responder = ApiResponder 10 | 11 | respond_to :json 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /app/helpers/power_api/application_helper.rb: -------------------------------------------------------------------------------- 1 | module PowerApi 2 | module ApplicationHelper 3 | VALID_SERIALIZER_OUTPUT_FORMATS = %i{json hash} 4 | 5 | def serialize_resource(resource, options = {}) 6 | load_default_serializer_options(options) 7 | serialized_data = serialize_data(resource, options) 8 | render_serialized_data(serialized_data, options) 9 | rescue NoMethodError => e 10 | if e.message.include?("undefined method `serializable_hash'") 11 | raise ::PowerApi::InvalidSerializableResource.new( 12 | "Invalid #{resource.class} resource given. Must be ActiveRecord instance or collection" 13 | ) 14 | else 15 | raise e 16 | end 17 | end 18 | 19 | private 20 | 21 | def serialize_data(resource, options) 22 | return {} if resource.nil? 23 | 24 | serializable = ActiveModelSerializers::SerializableResource.new(resource, options) 25 | serializable.serializable_hash 26 | end 27 | 28 | def render_serialized_data(serialized_data, options) 29 | output_format = options.delete(:output_format) 30 | serialized_data = serialized_data.fetch(:root, serialized_data) 31 | return serialized_data if output_format == :hash 32 | 33 | serialized_data.presence.to_json 34 | end 35 | 36 | def load_default_serializer_options(options) 37 | options[:namespace] ||= "Api::Internal" 38 | options[:key_transform] ||= :camel_lower 39 | options[:include_root] ||= false 40 | options[:output_format] = format_serializer_output_format!(options[:output_format]) 41 | options[:key_transform] = :unaltered if options[:output_format] == :hash 42 | 43 | load_root_option(options) 44 | options 45 | end 46 | 47 | def load_root_option(options) 48 | return if !!options.delete(:include_root) 49 | 50 | options[:root] = :root 51 | end 52 | 53 | def format_serializer_output_format!(output_format) 54 | return :json if output_format.blank? 55 | 56 | output_format = output_format.to_s.to_sym 57 | 58 | if !VALID_SERIALIZER_OUTPUT_FORMATS.include?(output_format) 59 | raise ::PowerApi::InvalidSerializerOutputFormat.new( 60 | "Only #{VALID_SERIALIZER_OUTPUT_FORMATS} values are allowed." 61 | ) 62 | end 63 | 64 | output_format 65 | end 66 | end 67 | end 68 | -------------------------------------------------------------------------------- /app/jobs/power_api/application_job.rb: -------------------------------------------------------------------------------- 1 | module PowerApi 2 | class ApplicationJob < ActiveJob::Base 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/mailers/power_api/application_mailer.rb: -------------------------------------------------------------------------------- 1 | module PowerApi 2 | class ApplicationMailer < ActionMailer::Base 3 | default from: 'from@example.com' 4 | layout 'mailer' 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /app/models/power_api/application_record.rb: -------------------------------------------------------------------------------- 1 | module PowerApi 2 | class ApplicationRecord < ActiveRecord::Base 3 | self.abstract_class = true 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /app/responders/api_responder.rb: -------------------------------------------------------------------------------- 1 | class ApiResponder < ActionController::Responder 2 | def api_behavior 3 | raise MissingRenderer.new(format) unless has_renderer? 4 | 5 | if delete? 6 | head :no_content 7 | elsif post? 8 | display resource, status: :created 9 | else 10 | display resource 11 | end 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /app/views/layouts/power_api/application.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Power api 5 | <%= stylesheet_link_tag "power_api/application", media: "all" %> 6 | <%= javascript_include_tag "power_api/application" %> 7 | <%= csrf_meta_tags %> 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /bin/clean_test_app: -------------------------------------------------------------------------------- 1 | git checkout spec/dummy/*.rb 2 | git status --porcelain | cut -c 3-10000000 | grep 'dummy' | xargs rm -rf -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # This command will automatically be run when you run "rails" with Rails gems 3 | # installed from the root of your application. 4 | 5 | ENGINE_ROOT = File.expand_path('../..', __FILE__) 6 | ENGINE_PATH = File.expand_path('../../lib/power_api/engine', __FILE__) 7 | APP_PATH = File.expand_path('../../spec/dummy/config/application', __FILE__) 8 | 9 | # Set up gems listed in the Gemfile. 10 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 11 | require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) 12 | 13 | require 'rails/all' 14 | require 'rails/engine/commands' 15 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | PowerApi::Engine.routes.draw do 2 | end 3 | -------------------------------------------------------------------------------- /lib/generators/power_api/controller/USAGE: -------------------------------------------------------------------------------- 1 | Description: 2 | Create a new API controller for a given version 3 | 4 | Example: 5 | rails generate power_api:controller blog 6 | -------------------------------------------------------------------------------- /lib/generators/power_api/controller/controller_generator.rb: -------------------------------------------------------------------------------- 1 | class PowerApi::ControllerGenerator < Rails::Generators::NamedBase 2 | source_root File.expand_path('templates', __dir__) 3 | 4 | def self.valid_actions 5 | PowerApi::GeneratorHelpers::PERMITTED_ACTIONS 6 | end 7 | 8 | class_option( 9 | :attributes, 10 | type: 'array', 11 | default: [], 12 | aliases: '-a', 13 | desc: 'attributes to show in serializer' 14 | ) 15 | 16 | class_option( 17 | :controller_actions, 18 | type: 'array', 19 | default: [], 20 | desc: "actions to include in controller. Valid values: #{valid_actions.join(', ')}" 21 | ) 22 | 23 | class_option( 24 | :version_number, 25 | type: 'numeric', 26 | default: nil, 27 | aliases: '-v', 28 | desc: 'the API version number you want to add this controller. '\ 29 | 'Omitting this attribute will create a controller for the internal api.' 30 | ) 31 | 32 | class_option( 33 | :use_paginator, 34 | type: 'boolean', 35 | default: false, 36 | desc: 'to indicate whether the controller will use pager or not' 37 | ) 38 | 39 | class_option( 40 | :allow_filters, 41 | type: 'boolean', 42 | default: false, 43 | desc: 'to indicate whether the controller will allow query string filters or not' 44 | ) 45 | 46 | class_option( 47 | :authenticate_with, 48 | type: 'string', 49 | default: nil, 50 | desc: "to indicate if authorization is required to access the controller" 51 | ) 52 | 53 | class_option( 54 | :parent_resource, 55 | type: 'string', 56 | default: nil, 57 | desc: "to indicate if the current resource is nested in another" 58 | ) 59 | 60 | class_option( 61 | :owned_by_authenticated_resource, 62 | type: 'boolean', 63 | default: false, 64 | desc: "to indicate if the resource's owner must be the authorized resource" 65 | ) 66 | 67 | def create_controller 68 | create_file( 69 | helper.resource_controller_path, 70 | helper.resource_controller_tpl 71 | ) 72 | 73 | helper.format_ruby_file(helper.resource_controller_path) 74 | end 75 | 76 | def add_routes 77 | if helper.parent_resource? 78 | if helper.resource_actions? 79 | add_normal_route(actions: helper.controller_actions & ["show", "update", "destroy"]) 80 | end 81 | add_nested_route if helper.collection_actions? 82 | else 83 | add_normal_route(actions: helper.controller_actions) 84 | end 85 | 86 | helper.format_ruby_file(helper.routes_path) 87 | end 88 | 89 | def create_serializer 90 | create_file( 91 | helper.ams_serializer_path, 92 | helper.ams_serializer_tpl 93 | ) 94 | 95 | helper.format_ruby_file(helper.ams_serializer_path) 96 | end 97 | 98 | def add_rspec_tests 99 | create_file(helper.resource_spec_path, helper.resource_spec_tpl) 100 | helper.format_ruby_file(helper.resource_spec_path) 101 | end 102 | 103 | private 104 | 105 | def add_nested_route 106 | line_to_replace = helper.parent_resource_routes_line_regex 107 | nested_resource_line = helper.resource_route_tpl( 108 | actions: helper.controller_actions & ['index', 'create'] 109 | ) 110 | add_nested_parent_route unless helper.parent_route_exist? 111 | 112 | if helper.parent_route_already_have_children? 113 | add_route(line_to_replace) { |match| "#{match}\n#{nested_resource_line}" } 114 | else 115 | add_route(line_to_replace) do |match| 116 | "#{match.delete_suffix('\n')} do\n#{nested_resource_line}\nend\n" 117 | end 118 | end 119 | end 120 | 121 | def add_normal_route(actions:) 122 | actions_for_only_option = actions.sort == self.class.valid_actions.sort ? [] : actions 123 | add_route(helper.api_current_route_namespace_line_regex) do |match| 124 | "#{match}\n#{helper.resource_route_tpl(actions: actions_for_only_option)}" 125 | end 126 | end 127 | 128 | def add_nested_parent_route 129 | add_route(helper.api_current_route_namespace_line_regex) do |match| 130 | "#{match}\n#{helper.resource_route_tpl(is_parent: true)}" 131 | end 132 | end 133 | 134 | def add_route(line_to_replace, &block) 135 | gsub_file helper.routes_path, line_to_replace do |match| 136 | block.call(match) 137 | end 138 | end 139 | 140 | def helper 141 | @helper ||= PowerApi::GeneratorHelpers.new( 142 | version_number: options[:version_number], 143 | resource: file_name, 144 | authenticated_resource: options[:authenticate_with], 145 | parent_resource: options[:parent_resource], 146 | owned_by_authenticated_resource: options[:owned_by_authenticated_resource], 147 | resource_attributes: options[:attributes], 148 | controller_actions: options[:controller_actions], 149 | use_paginator: options[:use_paginator], 150 | allow_filters: options[:allow_filters] 151 | ) 152 | end 153 | end 154 | -------------------------------------------------------------------------------- /lib/generators/power_api/exposed_api_config/USAGE: -------------------------------------------------------------------------------- 1 | Description: 2 | Configure exposed API in host app. 3 | 4 | Example: 5 | rails generate power_api:exposed_api_config 6 | -------------------------------------------------------------------------------- /lib/generators/power_api/exposed_api_config/exposed_api_config_generator.rb: -------------------------------------------------------------------------------- 1 | class PowerApi::ExposedApiConfigGenerator < Rails::Generators::Base 2 | source_root File.expand_path('templates', __dir__) 3 | 4 | class_option( 5 | :authenticated_resources, 6 | type: 'array', 7 | default: [], 8 | desc: 'define which model or models will be token authenticatable' 9 | ) 10 | 11 | def add_base_controller 12 | create_file( 13 | helper.exposed_base_controller_path, 14 | helper.exposed_base_controller_tpl 15 | ) 16 | end 17 | 18 | def install_first_version 19 | generate "power_api:version 1" 20 | end 21 | 22 | def install_simple_token_auth 23 | create_file( 24 | helper.simple_token_auth_initializer_path, 25 | helper.simple_token_auth_initializer_tpl, 26 | force: true 27 | ) 28 | 29 | helper.authenticated_resources.each do |resource| 30 | generate resource.authenticated_resource_migration 31 | 32 | insert_into_file( 33 | resource.path, 34 | helper.simple_token_auth_method, 35 | after: resource.class_definition_line 36 | ) 37 | end 38 | end 39 | 40 | private 41 | 42 | def helper 43 | @helper ||= PowerApi::GeneratorHelpers.new( 44 | authenticated_resources: options[:authenticated_resources] 45 | ) 46 | end 47 | end 48 | -------------------------------------------------------------------------------- /lib/generators/power_api/install/USAGE: -------------------------------------------------------------------------------- 1 | Description: 2 | Install the engine in host app. 3 | 4 | Example: 5 | rails generate power_api:install 6 | -------------------------------------------------------------------------------- /lib/generators/power_api/install/install_generator.rb: -------------------------------------------------------------------------------- 1 | class PowerApi::InstallGenerator < Rails::Generators::Base 2 | source_root File.expand_path('templates', __dir__) 3 | 4 | def create_api_base_controller 5 | create_file(helper.api_main_base_controller_path, helper.api_main_base_controller_tpl) 6 | end 7 | 8 | def create_ams_initializer 9 | create_file(helper.ams_initializer_path, helper.ams_initializer_tpl) 10 | end 11 | 12 | def install_api_pagination 13 | create_file( 14 | helper.api_pagination_initializer_path, 15 | helper.api_pagination_initializer_tpl, 16 | force: true 17 | ) 18 | end 19 | 20 | private 21 | 22 | def helper 23 | @helper ||= PowerApi::GeneratorHelpers.new 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /lib/generators/power_api/internal_api_config/USAGE: -------------------------------------------------------------------------------- 1 | Description: 2 | Configure internal API in host app. 3 | 4 | Example: 5 | rails generate power_api:internal_api_config 6 | -------------------------------------------------------------------------------- /lib/generators/power_api/internal_api_config/internal_api_config_generator.rb: -------------------------------------------------------------------------------- 1 | class PowerApi::InternalApiConfigGenerator < Rails::Generators::Base 2 | source_root File.expand_path('templates', __dir__) 3 | 4 | def add_base_controller 5 | create_file( 6 | helper.internal_base_controller_path, 7 | helper.internal_base_controller_tpl 8 | ) 9 | end 10 | 11 | def modify_routes 12 | insert_into_file( 13 | helper.routes_path, 14 | after: helper.routes_first_line 15 | ) do 16 | helper.internal_route_tpl 17 | end 18 | 19 | helper.format_ruby_file(helper.routes_path) 20 | end 21 | 22 | def add_serializers_directory 23 | create_file(helper.ams_serializers_path) 24 | end 25 | 26 | private 27 | 28 | def helper 29 | @helper ||= PowerApi::GeneratorHelpers.new 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /lib/generators/power_api/version/USAGE: -------------------------------------------------------------------------------- 1 | Description: 2 | Creates new API version 3 | 4 | Example: 5 | rails generate power_api:version 1 6 | -------------------------------------------------------------------------------- /lib/generators/power_api/version/version_generator.rb: -------------------------------------------------------------------------------- 1 | class PowerApi::VersionGenerator < Rails::Generators::NamedBase 2 | source_root File.expand_path('templates', __dir__) 3 | 4 | def modify_routes 5 | insert_into_file( 6 | helper.routes_path, 7 | after: helper.routes_line_to_inject_new_version 8 | ) do 9 | helper.version_route_tpl 10 | end 11 | 12 | helper.format_ruby_file(helper.routes_path) 13 | end 14 | 15 | def add_base_controller 16 | create_file( 17 | helper.version_base_controller_path, 18 | helper.version_base_controller_tpl 19 | ) 20 | end 21 | 22 | def add_serializers_directory 23 | create_file(helper.ams_serializers_path) 24 | end 25 | 26 | private 27 | 28 | def helper 29 | @helper ||= PowerApi::GeneratorHelpers.new(version_number: file_name) 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /lib/power_api.rb: -------------------------------------------------------------------------------- 1 | require "active_model_serializers" 2 | require "api-pagination" 3 | require "kaminari" 4 | require "ransack" 5 | require "responders" 6 | require "simple_token_authentication" 7 | require "versionist" 8 | 9 | require "power_api/engine" 10 | 11 | module PowerApi 12 | extend self 13 | 14 | # You can add, in this module, your own configuration options as in the example below... 15 | # 16 | # attr_writer :my_option 17 | # 18 | # def my_option 19 | # return "Default Value" unless @my_option 20 | # @my_option 21 | # end 22 | # 23 | # Then, you can customize the default behaviour (typically in a Rails initializer) like this: 24 | # 25 | # PowerApi.setup do |config| 26 | # config.root_url = "Another value" 27 | # end 28 | 29 | def setup 30 | yield self 31 | require "power_api" 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /lib/power_api/engine.rb: -------------------------------------------------------------------------------- 1 | module PowerApi 2 | module GeneratorHelper; end 3 | 4 | class Engine < ::Rails::Engine 5 | isolate_namespace PowerApi 6 | 7 | config.generators do |g| 8 | g.test_framework :rspec, fixture: false 9 | g.fixture_replacement :factory_bot, dir: "spec/factories" 10 | end 11 | 12 | initializer "initialize" do 13 | require_relative "./errors" 14 | require_relative "./generator_helper/controller_actions_helper" 15 | require_relative "./generator_helper/active_record_resource" 16 | require_relative "./generator_helper/api_helper" 17 | require_relative "./generator_helper/resource_helper" 18 | require_relative "./generator_helper/ams_helper" 19 | require_relative "./generator_helper/rspec_controller_helper" 20 | require_relative "./generator_helper/controller_helper" 21 | require_relative "./generator_helper/routes_helper" 22 | require_relative "./generator_helper/pagination_helper" 23 | require_relative "./generator_helper/simple_token_auth_helper" 24 | require_relative "./generator_helper/rubocop_helper" 25 | require_relative "./generator_helper/template_builder_helper" 26 | require_relative "./generator_helpers" 27 | end 28 | 29 | initializer "power_api.view_helpers" do 30 | ActiveSupport.on_load(:action_view) { include ::PowerApi::ApplicationHelper } 31 | end 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /lib/power_api/errors.rb: -------------------------------------------------------------------------------- 1 | module PowerApi 2 | class GeneratorError < StandardError; end 3 | class InvalidVersion < StandardError; end 4 | class InvalidSerializerOutputFormat < StandardError; end 5 | class InvalidSerializableResource < StandardError; end 6 | end 7 | -------------------------------------------------------------------------------- /lib/power_api/generator_helper/active_record_resource.rb: -------------------------------------------------------------------------------- 1 | # rubocop:disable Metrics/ModuleLength 2 | module PowerApi::GeneratorHelper::ActiveRecordResource 3 | extend ActiveSupport::Concern 4 | 5 | included do 6 | attr_reader :resource_attributes 7 | end 8 | 9 | def resource_name=(value) 10 | @resource_name = value 11 | 12 | if !resource_class 13 | raise PowerApi::GeneratorError.new( 14 | "Invalid resource name. Must be the snake_case representation of a ruby class" 15 | ) 16 | end 17 | 18 | if !resource_is_active_record_model? 19 | raise PowerApi::GeneratorError.new("resource is not an active record model") 20 | end 21 | end 22 | 23 | def resource_attributes=(collection) 24 | attributes = format_attributes(collection) 25 | 26 | if attributes.count == 1 && attributes.first[:name] == :id 27 | raise PowerApi::GeneratorError.new("at least one attribute must be added") 28 | end 29 | 30 | @resource_attributes = attributes 31 | end 32 | 33 | def id 34 | "#{snake_case}_id" 35 | end 36 | 37 | def upcase 38 | snake_case.upcase 39 | end 40 | 41 | def upcase_plural 42 | plural.upcase 43 | end 44 | 45 | def camel 46 | resource_name.camelize 47 | end 48 | 49 | def camel_plural 50 | camel.pluralize 51 | end 52 | 53 | def plural 54 | snake_case.pluralize 55 | end 56 | 57 | def snake_case 58 | resource_name.underscore 59 | end 60 | 61 | def titleized 62 | resource_name.titleize 63 | end 64 | 65 | def plural_titleized 66 | plural.titleize 67 | end 68 | 69 | def path 70 | "app/models/#{snake_case}.rb" 71 | end 72 | 73 | def class_definition_line 74 | "class #{camel} < ApplicationRecord\n" 75 | end 76 | 77 | def attributes_names 78 | extract_attrs_names(resource_attributes) 79 | end 80 | 81 | def required_attributes_names 82 | extract_attrs_names(required_resource_attributes) 83 | end 84 | 85 | def permitted_attributes_names 86 | extract_attrs_names(permitted_attributes) 87 | end 88 | 89 | def permitted_attributes 90 | resource_attributes.reject do |attr| 91 | [:created_at, :updated_at, :id].include?(attr[:name]) 92 | end 93 | end 94 | 95 | def required_resource_attributes(include_id: false) 96 | resource_attributes.select do |attr| 97 | attr[:required] || (include_id && attr[:name] == :id) 98 | end 99 | end 100 | 101 | def optional_resource_attributes 102 | permitted_attributes.reject { |attr| attr[:required] } 103 | end 104 | 105 | def attributes_symbols_text_list 106 | attrs_to_symobls_text_list(attributes_names) 107 | end 108 | 109 | def permitted_attributes_symbols_text_list 110 | attrs_to_symobls_text_list(permitted_attributes_names) 111 | end 112 | 113 | private 114 | 115 | def resource_name 116 | @resource_name 117 | end 118 | 119 | def extract_attrs_names(attrs) 120 | attrs.map { |attr| attr[:name] } 121 | end 122 | 123 | def attrs_to_symobls_text_list(attrs) 124 | attrs.map { |a| ":#{a}" }.join(",\n") + "\n" 125 | end 126 | 127 | def format_attributes(attrs) 128 | columns = resource_class.columns.inject([]) do |memo, col| 129 | col_name = col.name.to_sym 130 | 131 | memo << { 132 | name: col_name, 133 | type: col.type, 134 | required: required_attribute?(col_name), 135 | example: get_attribute_example(col.type, col_name) 136 | } 137 | 138 | memo 139 | end 140 | 141 | return columns if attrs.blank? 142 | 143 | attrs = (attrs.map(&:to_sym) + [:id]).uniq 144 | columns.select { |col| attrs.include?(col[:name]) } 145 | end 146 | 147 | def get_attribute_example(data_type, col_name) 148 | case data_type 149 | when :date 150 | "'1984-06-04'" 151 | when :datetime 152 | "'1984-06-04 09:00'" 153 | when :integer 154 | 666 155 | when :float, :decimal 156 | 6.66 157 | when :boolean 158 | true 159 | else 160 | "'Some #{col_name}'" 161 | end 162 | end 163 | 164 | def required_attribute?(col_name) 165 | validator_names = resource_class.validators_on(col_name).map do |validator| 166 | validator.class.name 167 | end 168 | 169 | validator_names.include?("ActiveRecord::Validations::PresenceValidator") 170 | end 171 | 172 | def resource_class 173 | resource_name.classify.constantize 174 | rescue NameError 175 | false 176 | end 177 | 178 | def resource_is_active_record_model? 179 | !!ActiveRecord::Base.descendants.find { |model_class| model_class == resource_class } 180 | end 181 | end 182 | # rubocop:enable Metrics/ModuleLength 183 | -------------------------------------------------------------------------------- /lib/power_api/generator_helper/ams_helper.rb: -------------------------------------------------------------------------------- 1 | module PowerApi::GeneratorHelper::AmsHelper 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | include PowerApi::GeneratorHelper::ApiHelper 6 | include PowerApi::GeneratorHelper::ResourceHelper 7 | end 8 | 9 | def ams_initializer_path 10 | "config/initializers/active_model_serializers.rb" 11 | end 12 | 13 | def ams_serializer_path 14 | "app/serializers/#{api_file_path}/#{resource.snake_case}_serializer.rb" 15 | end 16 | 17 | def ams_serializers_path 18 | "app/serializers/#{api_file_path}/.gitkeep" 19 | end 20 | 21 | def ams_initializer_tpl 22 | <<~INITIALIZER 23 | ActiveModelSerializers.config.adapter = :json 24 | INITIALIZER 25 | end 26 | 27 | def ams_serializer_tpl 28 | <<~SERIALIZER 29 | class #{api_class}::#{resource.camel}Serializer < ActiveModel::Serializer 30 | type :#{resource.snake_case} 31 | 32 | attributes( 33 | #{resource.attributes_symbols_text_list}) 34 | end 35 | SERIALIZER 36 | end 37 | end 38 | -------------------------------------------------------------------------------- /lib/power_api/generator_helper/api_helper.rb: -------------------------------------------------------------------------------- 1 | module PowerApi::GeneratorHelper::ApiHelper 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | attr_reader :version_number 6 | end 7 | 8 | def version_number=(value) 9 | if value.blank? 10 | @version_number = nil 11 | return 12 | end 13 | 14 | @version_number = value.to_s.to_i 15 | raise PowerApi::GeneratorError.new("invalid version number") if version_number < 1 16 | end 17 | 18 | def first_version? 19 | version_number.to_i == 1 20 | end 21 | 22 | def versioned_api? 23 | !!version_number 24 | end 25 | 26 | def api_file_path 27 | return version_file_path if versioned_api? 28 | 29 | internal_file_path 30 | end 31 | 32 | def version_file_path 33 | "#{exposed_file_path}/v#{version_number}" 34 | end 35 | 36 | def internal_file_path 37 | "api/internal" 38 | end 39 | 40 | def exposed_file_path 41 | "api/exposed" 42 | end 43 | 44 | def api_class 45 | return version_class if versioned_api? 46 | 47 | internal_class 48 | end 49 | 50 | def version_class 51 | "#{exposed_class}::V#{version_number}" 52 | end 53 | 54 | def internal_class 55 | "Api::Internal" 56 | end 57 | 58 | def exposed_class 59 | "Api::Exposed" 60 | end 61 | end 62 | -------------------------------------------------------------------------------- /lib/power_api/generator_helper/controller_actions_helper.rb: -------------------------------------------------------------------------------- 1 | module PowerApi::GeneratorHelper::ControllerActionsHelper 2 | extend ActiveSupport::Concern 3 | 4 | PERMITTED_ACTIONS = ['index', 'create', 'show', 'update', 'destroy'] 5 | 6 | attr_reader :controller_actions 7 | 8 | def controller_actions=(actions) 9 | @controller_actions = actions.blank? ? PERMITTED_ACTIONS : actions & PERMITTED_ACTIONS 10 | end 11 | 12 | PERMITTED_ACTIONS.each do |action| 13 | define_method("#{action}?") { controller_actions.include?(action) } 14 | end 15 | 16 | def resource_actions? 17 | show? || update? || destroy? 18 | end 19 | 20 | def collection_actions? 21 | index? || create? 22 | end 23 | 24 | def update_or_create? 25 | update? || create? 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /lib/power_api/generator_helper/controller_helper.rb: -------------------------------------------------------------------------------- 1 | # rubocop:disable Metrics/ModuleLength 2 | module PowerApi::GeneratorHelper::ControllerHelper 3 | extend ActiveSupport::Concern 4 | 5 | included do 6 | include PowerApi::GeneratorHelper::ApiHelper 7 | include PowerApi::GeneratorHelper::ResourceHelper 8 | include PowerApi::GeneratorHelper::PaginationHelper 9 | include PowerApi::GeneratorHelper::SimpleTokenAuthHelper 10 | include PowerApi::GeneratorHelper::TemplateBuilderHelper 11 | include PowerApi::GeneratorHelper::ControllerActionsHelper 12 | 13 | attr_accessor :allow_filters 14 | end 15 | 16 | def api_main_base_controller_path 17 | "app/controllers/api/base_controller.rb" 18 | end 19 | 20 | def exposed_base_controller_path 21 | "app/controllers/#{exposed_file_path}/base_controller.rb" 22 | end 23 | 24 | def internal_base_controller_path 25 | "app/controllers/#{internal_file_path}/base_controller.rb" 26 | end 27 | 28 | def version_base_controller_path 29 | "app/controllers/#{version_file_path}/base_controller.rb" 30 | end 31 | 32 | def resource_controller_path 33 | "app/controllers/#{api_file_path}/#{resource.plural}_controller.rb" 34 | end 35 | 36 | def api_main_base_controller_tpl 37 | <<~CONTROLLER 38 | class Api::BaseController < PowerApi::BaseController 39 | end 40 | CONTROLLER 41 | end 42 | 43 | def exposed_base_controller_tpl 44 | <<~CONTROLLER 45 | class #{exposed_class}::BaseController < Api::BaseController 46 | skip_before_action :verify_authenticity_token 47 | end 48 | CONTROLLER 49 | end 50 | 51 | def internal_base_controller_tpl 52 | <<~CONTROLLER 53 | class #{internal_class}::BaseController < Api::BaseController 54 | before_action do 55 | self.namespace_for_serializer = ::#{internal_class} 56 | end 57 | end 58 | CONTROLLER 59 | end 60 | 61 | def version_base_controller_tpl 62 | <<~CONTROLLER 63 | class #{version_class}::BaseController < #{exposed_class}::BaseController 64 | before_action do 65 | self.namespace_for_serializer = ::#{version_class} 66 | end 67 | end 68 | CONTROLLER 69 | end 70 | 71 | def resource_controller_tpl 72 | tpl_class( 73 | ctrl_tpl_class_definition_line, 74 | ctrl_tpl_authentication_code, 75 | ctrl_tpl_index, 76 | ctrl_tpl_show, 77 | ctrl_tpl_create, 78 | ctrl_tpl_update, 79 | ctrl_tpl_destroy, 80 | "private", 81 | ctrl_tpl_resource, 82 | ctrl_tpl_resources_from_authenticated_resource, 83 | ctrl_tpl_find_parent_resource, 84 | ctrl_tpl_permitted_params 85 | ) 86 | end 87 | 88 | private 89 | 90 | def ctrl_tpl_class_definition_line 91 | "#{api_class}::#{resource.camel_plural}Controller < #{api_class}::BaseController" 92 | end 93 | 94 | def ctrl_tpl_authentication_code 95 | return unless authenticated_resource? 96 | 97 | if versioned_api? 98 | return "acts_as_token_authentication_handler_for #{authenticated_resource.camel}, \ 99 | fallback: :exception\n" 100 | end 101 | 102 | "before_action :authenticate_#{authenticated_resource.snake_case}!\n" 103 | end 104 | 105 | def ctrl_tpl_index 106 | return unless index? 107 | 108 | concat_tpl_method("index", "respond_with #{ctrl_tpl_index_resources}") 109 | end 110 | 111 | def ctrl_tpl_show 112 | return unless show? 113 | 114 | concat_tpl_method("show", "respond_with #{resource.snake_case}") 115 | end 116 | 117 | def ctrl_tpl_create 118 | return unless create? 119 | 120 | concat_tpl_method("create", "respond_with #{ctrl_tpl_create_resource}") 121 | end 122 | 123 | def ctrl_tpl_update 124 | return unless update? 125 | 126 | concat_tpl_method( 127 | "update", 128 | "#{resource.snake_case}.update!(#{resource.snake_case}_params)", 129 | "respond_with #{resource.snake_case}" 130 | ) 131 | end 132 | 133 | def ctrl_tpl_destroy 134 | return unless destroy? 135 | 136 | concat_tpl_method("destroy", "respond_with #{resource.snake_case}.destroy!") 137 | end 138 | 139 | def ctrl_tpl_resource 140 | return unless resource_actions? 141 | 142 | concat_tpl_method(resource.snake_case, "@#{resource.snake_case} ||= #{ctrl_tpl_find_resource}") 143 | end 144 | 145 | def ctrl_tpl_permitted_params 146 | return unless update_or_create? 147 | 148 | concat_tpl_method( 149 | "#{resource.snake_case}_params", 150 | "params.require(:#{resource.snake_case}).permit(", 151 | "#{resource.permitted_attributes_symbols_text_list})" 152 | ) 153 | end 154 | 155 | def ctrl_tpl_find_resource 156 | find_statement = "find_by!(id: params[:id])" 157 | resource_source = if owned_by_authenticated_resource? 158 | if parent_resource? 159 | "#{resource.camel}.where(#{parent_resource.snake_case}: \ 160 | #{current_authenticated_resource}.#{parent_resource.plural})" 161 | else 162 | resource.plural 163 | end 164 | else 165 | resource.camel 166 | end 167 | 168 | "#{resource_source}.#{find_statement}" 169 | end 170 | 171 | def ctrl_tpl_index_resources 172 | return ctrl_tpl_index_collection unless use_paginator 173 | 174 | "paginate(#{ctrl_tpl_index_collection})" 175 | end 176 | 177 | def ctrl_tpl_index_collection 178 | collection = owned_resource? ? resource.plural : "#{resource.camel}.all" 179 | return collection unless allow_filters 180 | 181 | "filtered_collection(#{collection})" 182 | end 183 | 184 | def ctrl_tpl_create_resource 185 | create_statement = "create!(#{resource.snake_case}_params)" 186 | 187 | if owned_resource? 188 | "#{resource.plural}.#{create_statement}" 189 | else 190 | "#{resource.camel}.#{create_statement}" 191 | end 192 | end 193 | 194 | def ctrl_tpl_resources_from_authenticated_resource 195 | return unless owned_resource? 196 | 197 | resource_source = if owned_by_authenticated_resource? && !parent_resource? 198 | current_authenticated_resource 199 | else 200 | parent_resource.snake_case 201 | end 202 | 203 | concat_tpl_method( 204 | resource.plural, 205 | "@#{resource.plural} ||= #{resource_source}.#{resource.plural}" 206 | ) 207 | end 208 | 209 | def ctrl_tpl_find_parent_resource 210 | return unless parent_resource? 211 | 212 | resource_source = if owned_by_authenticated_resource? 213 | "#{current_authenticated_resource}.#{parent_resource.plural}" 214 | else 215 | parent_resource.camel 216 | end 217 | 218 | concat_tpl_method( 219 | parent_resource.snake_case, 220 | "@#{parent_resource.snake_case} ||= #{resource_source}.\ 221 | find_by!(id: params[:#{parent_resource.id}])" 222 | ) 223 | end 224 | 225 | def owned_resource? 226 | owned_by_authenticated_resource? || parent_resource? 227 | end 228 | end 229 | # rubocop:enable Metrics/ModuleLength 230 | -------------------------------------------------------------------------------- /lib/power_api/generator_helper/pagination_helper.rb: -------------------------------------------------------------------------------- 1 | module PowerApi::GeneratorHelper::PaginationHelper 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | attr_accessor :use_paginator 6 | end 7 | 8 | def api_pagination_initializer_path 9 | "config/initializers/api_pagination.rb" 10 | end 11 | 12 | def api_pagination_initializer_tpl 13 | <<~API_PAGINATION 14 | ApiPagination.configure do |config| 15 | # If you have more than one gem included, you can choose a paginator. 16 | config.paginator = :kaminari 17 | 18 | # By default, this is set to 'Total' 19 | config.total_header = 'X-Total' 20 | 21 | # By default, this is set to 'Per-Page' 22 | config.per_page_header = 'X-Per-Page' 23 | 24 | # Optional: set this to add a header with the current page number. 25 | config.page_header = 'X-Page' 26 | 27 | # Optional: set this to add other response format. Useful with tools that define :jsonapi format 28 | # config.response_formats = [:json, :xml, :jsonapi] 29 | config.response_formats = [:jsonapi] 30 | 31 | # Optional: what parameter should be used to set the page option 32 | config.page_param do |params| 33 | params[:page][:number] if params[:page].is_a?(ActionController::Parameters) 34 | end 35 | 36 | # Optional: what parameter should be used to set the per page option 37 | config.per_page_param do |params| 38 | params[:page][:size] if params[:page].is_a?(ActionController::Parameters) 39 | end 40 | 41 | # Optional: Include the total and last_page link header 42 | # By default, this is set to true 43 | # Note: When using kaminari, this prevents the count call to the database 44 | config.include_total = true 45 | end 46 | API_PAGINATION 47 | end 48 | end 49 | -------------------------------------------------------------------------------- /lib/power_api/generator_helper/resource_helper.rb: -------------------------------------------------------------------------------- 1 | module PowerApi::GeneratorHelper::ResourceHelper 2 | extend ActiveSupport::Concern 3 | 4 | class Resource 5 | include PowerApi::GeneratorHelper::ActiveRecordResource 6 | 7 | def initialize(resource_name) 8 | self.resource_name = resource_name 9 | end 10 | end 11 | 12 | included do 13 | attr_reader :resource, :parent_resource 14 | end 15 | 16 | def resource=(value) 17 | @resource = Resource.new(value) 18 | end 19 | 20 | def parent_resource=(value) 21 | return if value.blank? 22 | 23 | @parent_resource = Resource.new(value) 24 | end 25 | 26 | def resource_attributes=(collection) 27 | resource.resource_attributes = collection 28 | end 29 | 30 | def parent_resource? 31 | !!parent_resource 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /lib/power_api/generator_helper/routes_helper.rb: -------------------------------------------------------------------------------- 1 | # rubocop:disable Layout/AlignParameters 2 | module PowerApi::GeneratorHelper::RoutesHelper 3 | extend ActiveSupport::Concern 4 | 5 | included do 6 | include PowerApi::GeneratorHelper::ApiHelper 7 | include PowerApi::GeneratorHelper::ResourceHelper 8 | include PowerApi::GeneratorHelper::TemplateBuilderHelper 9 | end 10 | 11 | def routes_path 12 | "config/routes.rb" 13 | end 14 | 15 | def routes_line_to_inject_new_version 16 | return routes_first_line if first_version? 17 | 18 | "'/api' do\n" 19 | end 20 | 21 | def routes_first_line 22 | "routes.draw do\n" 23 | end 24 | 25 | def api_current_route_namespace_line_regex 26 | return /#{version_class}[^\n]*/ if versioned_api? 27 | 28 | /namespace :internal[^\n]*/ 29 | end 30 | 31 | def parent_resource_routes_line_regex 32 | /#{parent_resource_route_tpl}[^\n]*/ 33 | end 34 | 35 | def version_route_tpl 36 | return first_version_route_tpl if first_version? 37 | 38 | new_version_route_tpl 39 | end 40 | 41 | def internal_route_tpl 42 | concat_tpl_statements( 43 | "namespace :api, defaults: { format: :json } do", 44 | "namespace :internal do", 45 | "end", 46 | "end\n" 47 | ) 48 | end 49 | 50 | def resource_route_tpl(actions: [], is_parent: false) 51 | res = (is_parent ? parent_resource : resource).plural 52 | line = "resources :#{res}" 53 | line += ", only: [#{actions.map { |a| ":#{a}" }.join(', ')}]" if actions.any? 54 | line 55 | end 56 | 57 | def parent_route_exist? 58 | routes_match_regex?(/#{parent_resource_route_tpl}/) 59 | end 60 | 61 | def parent_route_already_have_children? 62 | routes_match_regex?(/#{parent_resource_route_tpl}[\W\w]*do/) 63 | end 64 | 65 | private 66 | 67 | def resource_route_statements(actions: []) 68 | line = "resources :#{resource.plural}" 69 | line += ", only: [#{actions.map { |a| ":#{a}" }.join(', ')}]" if actions.any? 70 | line 71 | end 72 | 73 | def routes_match_regex?(regex) 74 | path = File.join(Rails.root, routes_path) 75 | File.readlines(path).grep(regex).any? 76 | end 77 | 78 | def parent_resource_route_tpl 79 | raise PowerApi::GeneratorError.new("missing parent_resource") unless parent_resource? 80 | 81 | "resources :#{parent_resource.plural}" 82 | end 83 | 84 | def first_version_route_tpl 85 | concat_tpl_statements( 86 | "scope path: '/api' do", 87 | "api_version(#{api_version_params}) do", 88 | "end", 89 | "end\n" 90 | ) 91 | end 92 | 93 | def new_version_route_tpl 94 | concat_tpl_statements( 95 | "api_version(#{api_version_params}) do", 96 | "end" 97 | ) 98 | end 99 | 100 | def api_version_params 101 | "module: '#{version_class}', \ 102 | path: { value: 'v#{version_number}' }, \ 103 | defaults: { format: 'json' }" 104 | end 105 | end 106 | # rubocop:enable Layout/AlignParameters 107 | -------------------------------------------------------------------------------- /lib/power_api/generator_helper/rspec_controller_helper.rb: -------------------------------------------------------------------------------- 1 | # rubocop:disable Metrics/ModuleLength 2 | # rubocop:disable Metrics/MethodLength 3 | # rubocop:disable Layout/AlignParameters 4 | module PowerApi::GeneratorHelper::RspecControllerHelper 5 | extend ActiveSupport::Concern 6 | 7 | included do 8 | include PowerApi::GeneratorHelper::ApiHelper 9 | include PowerApi::GeneratorHelper::ResourceHelper 10 | include PowerApi::GeneratorHelper::TemplateBuilderHelper 11 | end 12 | 13 | def resource_spec_path 14 | "spec/requests/#{api_file_path}/#{resource.plural}_spec.rb" 15 | end 16 | 17 | def resource_spec_tpl 18 | concat_tpl_statements( 19 | "require 'rails_helper'\n", 20 | concat_tpl_statements( 21 | spec_initial_describe_line, 22 | spec_authenticated_resource_tpl, 23 | spec_let_parent_resource_tpl, 24 | spec_index_tpl, 25 | spec_create_tpl, 26 | spec_show_tpl, 27 | spec_update_tpl, 28 | spec_destroy_tpl, 29 | "end\n" 30 | ) 31 | ) 32 | end 33 | 34 | private 35 | 36 | def spec_initial_describe_line 37 | "RSpec.describe '#{api_class}::#{resource.camel_plural}Controllers', type: :request do" 38 | end 39 | 40 | def spec_authenticated_resource_tpl 41 | return unless authenticated_resource? 42 | 43 | res_name = authenticated_resource.snake_case 44 | "let(:#{res_name}) { create(:#{res_name}) }" 45 | end 46 | 47 | def spec_let_parent_resource_tpl 48 | return unless parent_resource? 49 | 50 | concat_tpl_statements( 51 | "let(:#{parent_resource.snake_case}) { create(:#{parent_resource.snake_case}) }", 52 | "let(:#{parent_resource.id}) { #{parent_resource.snake_case}.id }\n" 53 | ) 54 | end 55 | 56 | def spec_index_tpl 57 | return unless index? 58 | 59 | concat_tpl_statements( 60 | "describe 'GET /index' do", 61 | "let!(:#{resource.plural}) { #{spec_index_creation_list_tpl} }", 62 | "let(:collection) { JSON.parse(response.body)['#{resource.plural}'] }", 63 | "let(:params) { {} }\n", 64 | spec_perform_tpl, 65 | with_authorized_resource_context, 66 | perform_block_tpl, 67 | "it { expect(collection.count).to eq(5) }", 68 | "it { expect(response.status).to eq(200) }", 69 | if authenticated_resource? 70 | "end\n" 71 | end, 72 | unauthorized_spec_tpl, 73 | "end\n" 74 | ) 75 | end 76 | 77 | def spec_create_tpl 78 | return unless create? 79 | 80 | concat_tpl_statements( 81 | "describe 'POST /create' do", 82 | "let(:params) do", 83 | "{", 84 | "#{resource.snake_case}: {#{resource_parameters}", 85 | "}", 86 | "}", 87 | "end\n", 88 | let_resource_attrs, 89 | spec_perform_tpl(http_verb: 'post'), 90 | with_authorized_resource_context, 91 | perform_block_tpl, 92 | "it { expect(attributes).to include(params[:#{resource.snake_case}]) }", 93 | "it { expect(response.status).to eq(201) }", 94 | spec_invalid_attrs_test_tpl, 95 | if authenticated_resource? 96 | "end\n" 97 | end, 98 | unauthorized_spec_tpl, 99 | "end\n" 100 | ) 101 | end 102 | 103 | def spec_show_tpl 104 | return unless show? 105 | 106 | concat_tpl_statements( 107 | "describe 'GET /show' do", 108 | spec_let_existent_resource_tpl, 109 | "let(:#{resource.snake_case}_id) { #{resource.snake_case}.id.to_s }\n", 110 | let_resource_attrs, 111 | spec_perform_tpl(http_verb: 'get', params: false, single_resource: true), 112 | with_authorized_resource_context, 113 | perform_block_tpl, 114 | "it { expect(response.status).to eq(200) }\n", 115 | "context 'with resource not found' do", 116 | "let(:#{resource.snake_case}_id) { '666' }", 117 | "it { expect(response.status).to eq(404) }", 118 | "end", 119 | if authenticated_resource? 120 | "end\n" 121 | end, 122 | unauthorized_spec_tpl, 123 | "end\n" 124 | ) 125 | end 126 | 127 | def spec_update_tpl 128 | return unless update? 129 | 130 | concat_tpl_statements( 131 | "describe 'PUT /update' do", 132 | spec_let_existent_resource_tpl, 133 | "let(:#{resource.snake_case}_id) { #{resource.snake_case}.id.to_s }\n", 134 | "let(:params) do", 135 | "{", 136 | "#{resource.snake_case}: {#{resource_parameters}", 137 | "}", 138 | "}", 139 | "end\n", 140 | let_resource_attrs, 141 | spec_perform_tpl(http_verb: 'put', params: true, single_resource: true), 142 | with_authorized_resource_context, 143 | perform_block_tpl, 144 | "it { expect(attributes).to include(params[:#{resource.snake_case}]) }", 145 | "it { expect(response.status).to eq(200) }", 146 | spec_invalid_attrs_test_tpl, 147 | "context 'with resource not found' do", 148 | "let(:#{resource.snake_case}_id) { '666' }", 149 | "it { expect(response.status).to eq(404) }", 150 | "end", 151 | if authenticated_resource? 152 | "end\n" 153 | end, 154 | unauthorized_spec_tpl, 155 | "end\n" 156 | ) 157 | end 158 | 159 | def spec_destroy_tpl 160 | return unless destroy? 161 | 162 | concat_tpl_statements( 163 | "describe 'DELETE /destroy' do", 164 | spec_let_existent_resource_tpl, 165 | "let(:#{resource.snake_case}_id) { #{resource.snake_case}.id.to_s }\n", 166 | spec_perform_tpl(http_verb: 'delete', params: false, single_resource: true), 167 | with_authorized_resource_context, 168 | perform_block_tpl, 169 | "it { expect(response.status).to eq(204) }\n", 170 | "context 'with resource not found' do", 171 | "let(:#{resource.snake_case}_id) { '666' }", 172 | "it { expect(response.status).to eq(404) }", 173 | "end", 174 | if authenticated_resource? 175 | "end\n" 176 | end, 177 | unauthorized_spec_tpl, 178 | "end\n" 179 | ) 180 | end 181 | 182 | def spec_let_existent_resource_tpl 183 | statement = ["let(:#{resource.snake_case}) { create(:#{resource.snake_case}"] 184 | load_owner_resource_factory_option(statement) 185 | statement.join(', ') + ') }' 186 | end 187 | 188 | def spec_invalid_attrs_test_tpl 189 | return if resource.required_resource_attributes.blank? 190 | 191 | concat_tpl_statements( 192 | "\ncontext 'with invalid attributes' do", 193 | "let(:params) do", 194 | "{", 195 | "#{resource.snake_case}: {#{invalid_resource_params}}", 196 | "}", 197 | "end\n", 198 | "it { expect(response.status).to eq(400) }", 199 | "end\n" 200 | ) 201 | end 202 | 203 | def invalid_resource_params 204 | return unless resource.required_resource_attributes.any? 205 | 206 | for_each_schema_attribute([resource.required_resource_attributes.first]) do |attr| 207 | "#{attr[:name]}: nil," 208 | end 209 | end 210 | 211 | def for_each_schema_attribute(attributes) 212 | attributes.inject("") do |memo, attr| 213 | memo += "\n" 214 | memo += yield(attr) 215 | memo 216 | end.delete_suffix(",") 217 | end 218 | 219 | def with_authorized_resource_context 220 | if authenticated_resource? 221 | "context 'with authorized #{authenticated_resource.snake_case}' do" 222 | end 223 | end 224 | 225 | def let_resource_attrs 226 | concat_tpl_statements( 227 | "let(:attributes) do", 228 | "JSON.parse(response.body)['#{resource.snake_case}'].symbolize_keys", 229 | "end" 230 | ) 231 | end 232 | 233 | def perform_block_tpl(auth: true) 234 | concat_tpl_statements( 235 | "before do", 236 | if auth && authenticated_resource? 237 | "sign_in(#{authenticated_resource.snake_case})" 238 | end, 239 | "perform", 240 | "end\n" 241 | ) 242 | end 243 | 244 | def spec_perform_tpl(http_verb: 'get', params: true, single_resource: false) 245 | body = "#{http_verb} '/#{spec_collection_path(single_resource)}" 246 | body += "/' + #{resource.snake_case}_id" if single_resource 247 | body += "'" unless single_resource 248 | body += ", params: params" if params 249 | 250 | concat_tpl_statements( 251 | "def perform", 252 | body, 253 | "end\n" 254 | ) 255 | end 256 | 257 | def spec_collection_path(single_resource) 258 | path = ["api"] 259 | path << (versioned_api? ? "v#{version_number}" : "internal") 260 | 261 | if parent_resource? && !single_resource 262 | path << parent_resource.plural 263 | path << "' + #{parent_resource.snake_case}.id.to_s + '" 264 | end 265 | 266 | path << resource.plural 267 | path.join("/") 268 | end 269 | 270 | def spec_index_creation_list_tpl 271 | statement = ["create_list(:#{resource.snake_case}, 5"] 272 | load_owner_resource_factory_option(statement) 273 | statement.join(', ') + ')' 274 | end 275 | 276 | def load_owner_resource_factory_option(statement) 277 | if parent_resource? 278 | statement << "#{parent_resource.snake_case}: #{parent_resource.snake_case}" 279 | end 280 | 281 | if owned_by_authenticated_resource? 282 | statement << "#{authenticated_resource.snake_case}: #{authenticated_resource.snake_case}" 283 | end 284 | end 285 | 286 | def unauthorized_spec_tpl 287 | return unless authenticated_resource? 288 | 289 | authenticated_resource_name = authenticated_resource.snake_case 290 | concat_tpl_statements( 291 | "context 'with unauthenticated #{authenticated_resource_name}' do", 292 | "before { perform }\n", 293 | "it { expect(response.status).to eq(401) }", 294 | "end\n" 295 | ) 296 | end 297 | 298 | def resource_parameters 299 | attrs = if resource.required_resource_attributes.any? 300 | resource.required_resource_attributes 301 | else 302 | resource.optional_resource_attributes 303 | end 304 | 305 | for_each_attribute(attrs) do |attr| 306 | "#{attr[:name]}: #{attr[:example]}," 307 | end 308 | end 309 | 310 | def for_each_attribute(attributes) 311 | attributes.inject("") do |memo, attr| 312 | next memo if parent_resource && attr[:name] == parent_resource.id.to_sym 313 | 314 | memo += "\n" 315 | memo += yield(attr) 316 | memo 317 | end.delete_suffix(",") 318 | end 319 | end 320 | # rubocop:enable Metrics/ModuleLength 321 | # rubocop:enable Metrics/MethodLength 322 | # rubocop:enable Layout/AlignParameters 323 | -------------------------------------------------------------------------------- /lib/power_api/generator_helper/rubocop_helper.rb: -------------------------------------------------------------------------------- 1 | module PowerApi::GeneratorHelper::RubocopHelper 2 | extend ActiveSupport::Concern 3 | 4 | def format_ruby_file(path) 5 | return unless File.exist?(path) 6 | 7 | options, paths = RuboCop::Options.new.parse(["-a", "-fa", path]) 8 | runner = RuboCop::Runner.new(options, RuboCop::ConfigStore.new) 9 | runner.run(paths) 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /lib/power_api/generator_helper/simple_token_auth_helper.rb: -------------------------------------------------------------------------------- 1 | module PowerApi::GeneratorHelper::SimpleTokenAuthHelper 2 | extend ActiveSupport::Concern 3 | 4 | class SimpleTokenAuthResource 5 | include PowerApi::GeneratorHelper::ActiveRecordResource 6 | include PowerApi::GeneratorHelper::ResourceHelper 7 | 8 | def initialize(resource) 9 | self.resource_name = resource 10 | end 11 | 12 | def authenticated_resource_migration 13 | "migration add_authentication_token_to_#{plural} \ 14 | authentication_token:string{30}:uniq" 15 | end 16 | end 17 | 18 | included do 19 | attr_reader :authenticated_resources, :authenticated_resource 20 | attr_accessor :owned_by_authenticated_resource 21 | end 22 | 23 | def authenticated_resources=(values) 24 | @authenticated_resources = values.map { |value| SimpleTokenAuthResource.new(value) } 25 | end 26 | 27 | def authenticated_resource=(value) 28 | return if value.blank? 29 | 30 | @authenticated_resource = SimpleTokenAuthResource.new(value) 31 | end 32 | 33 | def authenticated_resource? 34 | !!authenticated_resource 35 | end 36 | 37 | def owned_by_authenticated_resource? 38 | owned_by_authenticated_resource && authenticated_resource? && !parent_resource? 39 | end 40 | 41 | def current_authenticated_resource 42 | "current_#{authenticated_resource.snake_case}" 43 | end 44 | 45 | def simple_token_auth_method 46 | <<-METHOD 47 | acts_as_token_authenticatable 48 | 49 | METHOD 50 | end 51 | 52 | def simple_token_auth_initializer_path 53 | "config/initializers/simple_token_authentication.rb" 54 | end 55 | 56 | def simple_token_auth_initializer_tpl 57 | <<~INITIALIZER 58 | SimpleTokenAuthentication.configure do |config| 59 | # Configure the session persistence policy after a successful sign in, 60 | # in other words, if the authentication token acts as a signin token. 61 | # If true, user is stored in the session and the authentication token and 62 | # email may be provided only once. 63 | # If false, users must provide their authentication token and email at every request. 64 | # config.sign_in_token = false 65 | 66 | # Configure the name of the HTTP headers watched for authentication. 67 | # 68 | # Default header names for a given token authenticatable entity follow the pattern: 69 | # { entity: { authentication_token: 'X-Entity-Token', email: 'X-Entity-Email'} } 70 | # 71 | # When several token authenticatable models are defined, custom header names 72 | # can be specified for none, any, or all of them. 73 | # 74 | # Note: when using the identifiers options, this option behaviour is modified. 75 | # Please see the example below. 76 | # 77 | # Examples 78 | # 79 | # Given User and SuperAdmin are token authenticatable, 80 | # When the following configuration is used: 81 | # `config.header_names = { super_admin: { authentication_token: 'X-Admin-Auth-Token' } }` 82 | # Then the token authentification handler for User watches the following headers: 83 | # `X-User-Token, X-User-Email` 84 | # And the token authentification handler for SuperAdmin watches the following headers: 85 | # `X-Admin-Auth-Token, X-SuperAdmin-Email` 86 | # 87 | # When the identifiers option is set: 88 | # `config.identifiers = { super_admin: :phone_number }` 89 | # Then both the header names identifier key and default value are modified accordingly: 90 | # `config.header_names = { super_admin: { phone_number: 'X-SuperAdmin-PhoneNumber' } }` 91 | # 92 | # config.header_names = { user: { authentication_token: 'X-User-Token', email: 'X-User-Email' } } 93 | 94 | # Configure the name of the attribute used to identify the user for authentication. 95 | # That attribute must exist in your model. 96 | # 97 | # The default identifiers follow the pattern: 98 | # { entity: 'email' } 99 | # 100 | # Note: the identifer must match your Devise configuration, 101 | # see https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-using-their-username-or-email-address#tell-devise-to-use-username-in-the-authentication_keys 102 | # 103 | # Note: setting this option does modify the header_names behaviour, 104 | # see the header_names section above. 105 | # 106 | # Example: 107 | # 108 | # `config.identifiers = { super_admin: 'phone_number', user: 'uuid' }` 109 | # 110 | # config.identifiers = { user: 'email' } 111 | 112 | # Configure the Devise trackable strategy integration. 113 | # 114 | # If true, tracking is disabled for token authentication: signing in through 115 | # token authentication won't modify the Devise trackable statistics. 116 | # 117 | # If false, given Devise trackable is configured for the relevant model, 118 | # then signing in through token authentication will be tracked as any other sign in. 119 | # 120 | # config.skip_devise_trackable = true 121 | end 122 | INITIALIZER 123 | end 124 | end 125 | -------------------------------------------------------------------------------- /lib/power_api/generator_helper/template_builder_helper.rb: -------------------------------------------------------------------------------- 1 | module PowerApi::GeneratorHelper::TemplateBuilderHelper 2 | extend ActiveSupport::Concern 3 | 4 | def concat_tpl_statements(*methods) 5 | methods.reject(&:blank?).join("\n") 6 | end 7 | 8 | def concat_tpl_method(method_name, *method_lines) 9 | concat_tpl_statements( 10 | "def #{method_name}", 11 | *method_lines, 12 | "end" 13 | ) 14 | end 15 | 16 | def tpl_class(class_def, *statements) 17 | concat_tpl_statements( 18 | "class #{class_def}", 19 | *statements, 20 | "end\n" 21 | ) 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /lib/power_api/generator_helpers.rb: -------------------------------------------------------------------------------- 1 | module PowerApi 2 | class GeneratorHelpers 3 | include GeneratorHelper::ControllerActionsHelper 4 | include GeneratorHelper::ResourceHelper 5 | include GeneratorHelper::ApiHelper 6 | include GeneratorHelper::RspecControllerHelper 7 | include GeneratorHelper::AmsHelper 8 | include GeneratorHelper::ControllerHelper 9 | include GeneratorHelper::RoutesHelper 10 | include GeneratorHelper::PaginationHelper 11 | include GeneratorHelper::SimpleTokenAuthHelper 12 | include GeneratorHelper::RubocopHelper 13 | 14 | def initialize(config = {}) 15 | config.each do |attribute, value| 16 | load_attribute(attribute, value) 17 | end 18 | end 19 | 20 | private 21 | 22 | def load_attribute(attribute, value) 23 | send("#{attribute}=", value) 24 | end 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /lib/power_api/version.rb: -------------------------------------------------------------------------------- 1 | module PowerApi 2 | VERSION = '2.1.1' 3 | end 4 | -------------------------------------------------------------------------------- /lib/tasks/power_api_tasks.rake: -------------------------------------------------------------------------------- 1 | # desc "Explaining what the task does" 2 | # task :power_api do 3 | # # Task goes here 4 | # end 5 | -------------------------------------------------------------------------------- /power_api.gemspec: -------------------------------------------------------------------------------- 1 | $:.push File.expand_path("../lib", __FILE__) 2 | 3 | # Maintain your gem"s version: 4 | require "power_api/version" 5 | 6 | # Describe your gem and declare its dependencies: 7 | Gem::Specification.new do |s| 8 | s.name = "power_api" 9 | s.version = PowerApi::VERSION 10 | s.authors = ["Platanus", "Leandro Segovia"] 11 | s.email = ["rubygems@platan.us", "ldlsegovia@gmail.com"] 12 | s.homepage = "https://github.com/platanus/power_api" 13 | s.summary = "Set of other gems and configurations designed to build incredible APIs" 14 | s.description = "It is a Rails engine that gathers a set of other gems and configurations designed to build incredible APIs" 15 | s.license = "MIT" 16 | 17 | s.files = `git ls-files`.split($/).reject { |fn| fn.start_with? "spec" } 18 | s.bindir = "exe" 19 | s.executables = s.files.grep(%r{^exe/}) { |f| File.basename(f) } 20 | s.test_files = Dir["spec/**/*"] 21 | 22 | s.add_dependency "rails", ">= 6.0" 23 | 24 | s.add_dependency "active_model_serializers", "~> 0.10.0" 25 | s.add_dependency "api-pagination" 26 | s.add_dependency "kaminari" 27 | s.add_dependency "ransack" 28 | s.add_dependency "responders" 29 | s.add_dependency "simple_token_authentication", "~> 1.0" 30 | s.add_dependency "versionist", "~> 1.0" 31 | 32 | s.add_development_dependency "coveralls" 33 | s.add_development_dependency "factory_bot_rails" 34 | s.add_development_dependency "guard-rspec" 35 | s.add_development_dependency "pry" 36 | s.add_development_dependency "pry-rails" 37 | s.add_development_dependency "rspec-rails" 38 | s.add_development_dependency "rspec_junit_formatter" 39 | s.add_development_dependency "rubocop", "0.65.0" 40 | s.add_development_dependency "rubocop-rspec" 41 | s.add_development_dependency "sqlite3", "~> 1.4.2" 42 | end 43 | -------------------------------------------------------------------------------- /spec/dummy/Rakefile: -------------------------------------------------------------------------------- 1 | # Add your own tasks in files placed in lib/tasks ending in .rake, 2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 3 | 4 | require_relative "config/application" 5 | 6 | Rails.application.load_tasks 7 | -------------------------------------------------------------------------------- /spec/dummy/app/assets/config/manifest.js: -------------------------------------------------------------------------------- 1 | //= link_tree ../images 2 | //= link_directory ../stylesheets .css 3 | //= link power_api_manifest.js 4 | -------------------------------------------------------------------------------- /spec/dummy/app/assets/images/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/platanus/power_api/fc84727c8772199266af4d66f88b2bdd6dd0c4f4/spec/dummy/app/assets/images/.keep -------------------------------------------------------------------------------- /spec/dummy/app/assets/stylesheets/application.css: -------------------------------------------------------------------------------- 1 | /* 2 | * This is a manifest file that'll be compiled into application.css, which will include all the files 3 | * listed below. 4 | * 5 | * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, 6 | * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path. 7 | * 8 | * You're free to add application-wide styles to this file and they'll appear at the bottom of the 9 | * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS 10 | * files in this directory. Styles in this file should be added after the last require_* statement. 11 | * It is generally better to create a new file per style scope. 12 | * 13 | *= require_tree . 14 | *= require_self 15 | */ 16 | -------------------------------------------------------------------------------- /spec/dummy/app/channels/application_cable/channel.rb: -------------------------------------------------------------------------------- 1 | module ApplicationCable 2 | class Channel < ActionCable::Channel::Base 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /spec/dummy/app/channels/application_cable/connection.rb: -------------------------------------------------------------------------------- 1 | module ApplicationCable 2 | class Connection < ActionCable::Connection::Base 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /spec/dummy/app/controllers/api/base_controller.rb: -------------------------------------------------------------------------------- 1 | class Api::BaseController < PowerApi::BaseController 2 | end 3 | -------------------------------------------------------------------------------- /spec/dummy/app/controllers/api/internal/base_controller.rb: -------------------------------------------------------------------------------- 1 | class Api::Internal::BaseController < Api::BaseController 2 | before_action do 3 | self.namespace_for_serializer = ::Api::Internal 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /spec/dummy/app/controllers/api/internal/blogs_controller.rb: -------------------------------------------------------------------------------- 1 | class Api::Internal::BlogsController < Api::Internal::BaseController 2 | def index 3 | respond_with Blog.all 4 | end 5 | 6 | def show 7 | respond_with blog 8 | end 9 | 10 | def create 11 | respond_with Blog.create!(blog_params) 12 | end 13 | 14 | def update 15 | blog.update!(blog_params) 16 | respond_with blog 17 | end 18 | 19 | def destroy 20 | respond_with blog.destroy! 21 | end 22 | 23 | private 24 | 25 | def blog 26 | @blog ||= Blog.find_by!(id: params[:id]) 27 | end 28 | 29 | def blog_params 30 | params.require(:blog).permit( 31 | :title, 32 | :body, 33 | :portfolio_id 34 | ) 35 | end 36 | end 37 | -------------------------------------------------------------------------------- /spec/dummy/app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::Base 2 | end 3 | -------------------------------------------------------------------------------- /spec/dummy/app/controllers/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/platanus/power_api/fc84727c8772199266af4d66f88b2bdd6dd0c4f4/spec/dummy/app/controllers/concerns/.keep -------------------------------------------------------------------------------- /spec/dummy/app/controllers/concerns/api/deprecated_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe 'Api::Deprecated', type: :controller do 4 | before do 5 | routes.draw { get :action1, to: "anonymous#action" } 6 | 7 | get :action 8 | end 9 | 10 | context "with deprecated action" do 11 | controller do 12 | include ::Api::Deprecated 13 | 14 | deprecate :action 15 | 16 | def action 17 | head :ok 18 | end 19 | end 20 | 21 | it { expect(response.status).to eq(200) } 22 | it { expect(response.headers["Deprecated"]).to eq(true) } 23 | end 24 | 25 | context "with deprecated action" do 26 | controller do 27 | include ::Api::Deprecated 28 | 29 | def action 30 | head :ok 31 | end 32 | end 33 | 34 | it { expect(response.status).to eq(200) } 35 | it { expect(response.headers["Deprecated"]).to be_nil } 36 | end 37 | end 38 | -------------------------------------------------------------------------------- /spec/dummy/app/controllers/concerns/api/error_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe 'Api::Error', type: :controller do 4 | before do 5 | routes.draw { get :action, to: "anonymous#action" } 6 | 7 | get :action 8 | end 9 | 10 | def response_body 11 | JSON.parse(response.body).deep_symbolize_keys 12 | end 13 | 14 | context "with Exception error" do 15 | let(:expected_response) do 16 | { 17 | detail: ":-(", 18 | message: "server_error", 19 | type: "RuntimeError" 20 | } 21 | end 22 | 23 | controller do 24 | include ::Api::Error 25 | 26 | def action 27 | raise ':-(' 28 | end 29 | end 30 | 31 | it { expect(response_body).to eq(expected_response) } 32 | it { expect(response.status).to eq(500) } 33 | end 34 | 35 | context "with ActiveRecord::RecordNotFound error" do 36 | let(:expected_response) do 37 | { 38 | detail: ":-(", 39 | message: "record_not_found" 40 | } 41 | end 42 | 43 | controller do 44 | include ::Api::Error 45 | 46 | def action 47 | raise ActiveRecord::RecordNotFound.new(":-(") 48 | end 49 | end 50 | 51 | it { expect(response_body).to eq(expected_response) } 52 | it { expect(response.status).to eq(404) } 53 | end 54 | 55 | context "with ActiveModel::ForbiddenAttributesError error" do 56 | let(:expected_response) do 57 | { 58 | detail: ":-(", 59 | message: "protected_attributes" 60 | } 61 | end 62 | 63 | controller do 64 | include ::Api::Error 65 | 66 | def action 67 | raise ActiveModel::ForbiddenAttributesError.new(":-(") 68 | end 69 | end 70 | 71 | it { expect(response_body).to eq(expected_response) } 72 | it { expect(response.status).to eq(400) } 73 | end 74 | 75 | context "with ActiveRecord::RecordInvalid error" do 76 | let(:expected_response) do 77 | { 78 | message: "invalid_attributes", 79 | errors: { 80 | body: ["can't be blank"], 81 | title: ["can't be blank"] 82 | } 83 | } 84 | end 85 | 86 | controller do 87 | include ::Api::Error 88 | 89 | def action 90 | raise Blog.create! 91 | end 92 | end 93 | 94 | it { expect(response_body).to eq(expected_response) } 95 | it { expect(response.status).to eq(400) } 96 | end 97 | end 98 | -------------------------------------------------------------------------------- /spec/dummy/app/controllers/concerns/api/filtered_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe 'Api::Filtered', type: :controller do 4 | let(:filters) do 5 | nil 6 | end 7 | 8 | controller do 9 | include ::Api::Filtered 10 | 11 | def action 12 | render json: filtered_collection(Blog.all) 13 | end 14 | end 15 | 16 | before do 17 | routes.draw { get :action, to: "anonymous#action" } 18 | 19 | create(:blog, title: "Lean's blog") 20 | create(:blog, title: "Santiago's blog") 21 | 22 | get :action, params: { q: filters } 23 | end 24 | 25 | def resources_count 26 | JSON.parse(response.body).count 27 | end 28 | 29 | it { expect(resources_count).to eq(2) } 30 | it { expect(response.status).to eq(200) } 31 | 32 | context "with filters" do 33 | let(:filters) do 34 | { 35 | title_cont: "Lean" 36 | } 37 | end 38 | 39 | it { expect(resources_count).to eq(1) } 40 | it { expect(response.status).to eq(200) } 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /spec/dummy/app/helpers/application_helper.rb: -------------------------------------------------------------------------------- 1 | module ApplicationHelper 2 | end 3 | -------------------------------------------------------------------------------- /spec/dummy/app/javascript/packs/application.js: -------------------------------------------------------------------------------- 1 | // This is a manifest file that'll be compiled into application.js, which will include all the files 2 | // listed below. 3 | // 4 | // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, 5 | // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. 6 | // 7 | // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the 8 | // compiled file. JavaScript code in this file should be added after the last require_* statement. 9 | // 10 | // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details 11 | // about supported directives. 12 | // 13 | //= require rails-ujs 14 | //= require activestorage 15 | //= require_tree . 16 | -------------------------------------------------------------------------------- /spec/dummy/app/jobs/application_job.rb: -------------------------------------------------------------------------------- 1 | class ApplicationJob < ActiveJob::Base 2 | # Automatically retry jobs that encountered a deadlock 3 | # retry_on ActiveRecord::Deadlocked 4 | 5 | # Most jobs are safe to ignore if the underlying records are no longer available 6 | # discard_on ActiveJob::DeserializationError 7 | end 8 | -------------------------------------------------------------------------------- /spec/dummy/app/mailers/application_mailer.rb: -------------------------------------------------------------------------------- 1 | class ApplicationMailer < ActionMailer::Base 2 | default from: 'from@example.com' 3 | layout 'mailer' 4 | end 5 | -------------------------------------------------------------------------------- /spec/dummy/app/models/application_record.rb: -------------------------------------------------------------------------------- 1 | class ApplicationRecord < ActiveRecord::Base 2 | self.abstract_class = true 3 | end 4 | -------------------------------------------------------------------------------- /spec/dummy/app/models/blog.rb: -------------------------------------------------------------------------------- 1 | class Blog < ApplicationRecord 2 | belongs_to :portfolio, required: false 3 | 4 | validates :title, :body, presence: true 5 | end 6 | -------------------------------------------------------------------------------- /spec/dummy/app/models/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/platanus/power_api/fc84727c8772199266af4d66f88b2bdd6dd0c4f4/spec/dummy/app/models/concerns/.keep -------------------------------------------------------------------------------- /spec/dummy/app/models/portfolio.rb: -------------------------------------------------------------------------------- 1 | class Portfolio < ApplicationRecord 2 | belongs_to :user 3 | 4 | validates :name, presence: true 5 | end 6 | -------------------------------------------------------------------------------- /spec/dummy/app/models/user.rb: -------------------------------------------------------------------------------- 1 | class User < ApplicationRecord 2 | has_many :portfolios 3 | end 4 | -------------------------------------------------------------------------------- /spec/dummy/app/serializers/api/internal/blog_serializer.rb: -------------------------------------------------------------------------------- 1 | class Api::Internal::BlogSerializer < ActiveModel::Serializer 2 | type :blog 3 | 4 | attributes( 5 | :id, 6 | :title, 7 | :body, 8 | :created_at, 9 | :updated_at, 10 | :portfolio_id 11 | ) 12 | end 13 | -------------------------------------------------------------------------------- /spec/dummy/app/views/layouts/application.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Dummy 5 | 6 | <%= csrf_meta_tags %> 7 | <%= csp_meta_tag %> 8 | 9 | <%= stylesheet_link_tag 'application', media: 'all' %> 10 | 11 | 12 | 13 | <%= yield %> 14 | 15 | 16 | -------------------------------------------------------------------------------- /spec/dummy/app/views/layouts/mailer.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | -------------------------------------------------------------------------------- /spec/dummy/app/views/layouts/mailer.text.erb: -------------------------------------------------------------------------------- 1 | <%= yield %> 2 | -------------------------------------------------------------------------------- /spec/dummy/bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | APP_PATH = File.expand_path('../config/application', __dir__) 3 | require_relative "../config/boot" 4 | require "rails/commands" 5 | -------------------------------------------------------------------------------- /spec/dummy/bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require_relative "../config/boot" 3 | require "rake" 4 | Rake.application.run 5 | -------------------------------------------------------------------------------- /spec/dummy/bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require "fileutils" 3 | 4 | # path to your application root. 5 | APP_ROOT = File.expand_path('..', __dir__) 6 | 7 | def system!(*args) 8 | system(*args) || abort("\n== Command #{args} failed ==") 9 | end 10 | 11 | FileUtils.chdir APP_ROOT do 12 | # This script is a way to set up or update your development environment automatically. 13 | # This script is idempotent, so that you can run it at any time and get an expectable outcome. 14 | # Add necessary setup steps to this file. 15 | 16 | puts '== Installing dependencies ==' 17 | system! 'gem install bundler --conservative' 18 | system('bundle check') || system!('bundle install') 19 | 20 | # puts "\n== Copying sample files ==" 21 | # unless File.exist?('config/database.yml') 22 | # FileUtils.cp 'config/database.yml.sample', 'config/database.yml' 23 | # end 24 | 25 | puts "\n== Preparing database ==" 26 | system! 'bin/rails db:prepare' 27 | 28 | puts "\n== Removing old logs and tempfiles ==" 29 | system! 'bin/rails log:clear tmp:clear' 30 | 31 | puts "\n== Restarting application server ==" 32 | system! 'bin/rails restart' 33 | end 34 | -------------------------------------------------------------------------------- /spec/dummy/config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require_relative "config/environment" 4 | 5 | run Rails.application 6 | Rails.application.load_server 7 | -------------------------------------------------------------------------------- /spec/dummy/config/application.rb: -------------------------------------------------------------------------------- 1 | require_relative "boot" 2 | 3 | require "rails/all" 4 | 5 | # Require the gems listed in Gemfile, including any gems 6 | # you've limited to :test, :development, or :production. 7 | Bundler.require(*Rails.groups) 8 | require "power_api" 9 | 10 | module Dummy 11 | class Application < Rails::Application 12 | config.load_defaults Rails::VERSION::STRING.to_f 13 | 14 | # Configuration for the application, engines, and railties goes here. 15 | # 16 | # These settings can be overridden in specific environments using the files 17 | # in config/environments, which are processed later. 18 | # 19 | # config.time_zone = "Central Time (US & Canada)" 20 | # config.eager_load_paths << Rails.root.join("extras") 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /spec/dummy/config/boot.rb: -------------------------------------------------------------------------------- 1 | # Set up gems listed in the Gemfile. 2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../Gemfile', __dir__) 3 | 4 | require "bundler/setup" if File.exist?(ENV["BUNDLE_GEMFILE"]) 5 | $LOAD_PATH.unshift File.expand_path('../../../lib', __dir__) 6 | -------------------------------------------------------------------------------- /spec/dummy/config/cable.yml: -------------------------------------------------------------------------------- 1 | development: 2 | adapter: async 3 | 4 | test: 5 | adapter: test 6 | 7 | production: 8 | adapter: redis 9 | url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> 10 | channel_prefix: dummy_production 11 | -------------------------------------------------------------------------------- /spec/dummy/config/database.yml: -------------------------------------------------------------------------------- 1 | development: 2 | adapter: sqlite3 3 | pool: 5 4 | timeout: 5000 5 | database: db/development.sqlite3 6 | 7 | test: 8 | adapter: sqlite3 9 | pool: 5 10 | timeout: 5000 11 | database: db/test.sqlite3 12 | 13 | production: 14 | adapter: sqlite3 15 | pool: 5 16 | timeout: 5000 17 | database: db/production.sqlite3 18 | -------------------------------------------------------------------------------- /spec/dummy/config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require_relative "application" 3 | 4 | # Initialize the Rails application. 5 | Rails.application.initialize! 6 | -------------------------------------------------------------------------------- /spec/dummy/config/environments/development.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/integer/time" 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # In the development environment your application's code is reloaded any time 7 | # it changes. This slows down response time but is perfect for development 8 | # since you don't have to restart the web server when you make code changes. 9 | config.cache_classes = false 10 | 11 | # Do not eager load code on boot. 12 | config.eager_load = false 13 | 14 | # Show full error reports. 15 | config.consider_all_requests_local = true 16 | 17 | # Enable/disable caching. By default caching is disabled. 18 | # Run rails dev:cache to toggle caching. 19 | if Rails.root.join('tmp', 'caching-dev.txt').exist? 20 | config.action_controller.perform_caching = true 21 | config.action_controller.enable_fragment_cache_logging = true 22 | 23 | config.cache_store = :memory_store 24 | config.public_file_server.headers = { 25 | 'Cache-Control' => "public, max-age=#{2.days.to_i}" 26 | } 27 | else 28 | config.action_controller.perform_caching = false 29 | 30 | config.cache_store = :null_store 31 | end 32 | 33 | # Store uploaded files on the local file system (see config/storage.yml for options). 34 | config.active_storage.service = :local 35 | 36 | # Don't care if the mailer can't send. 37 | config.action_mailer.raise_delivery_errors = false 38 | 39 | config.action_mailer.perform_caching = false 40 | 41 | # Print deprecation notices to the Rails logger. 42 | config.active_support.deprecation = :log 43 | 44 | # Raise exceptions for disallowed deprecations. 45 | config.active_support.disallowed_deprecation = :raise 46 | 47 | # Tell Active Support which deprecation messages to disallow. 48 | config.active_support.disallowed_deprecation_warnings = [] 49 | 50 | # Raise an error on page load if there are pending migrations. 51 | config.active_record.migration_error = :page_load 52 | 53 | # Highlight code that triggered database queries in logs. 54 | config.active_record.verbose_query_logs = true 55 | 56 | # Debug mode disables concatenation and preprocessing of assets. 57 | # This option may cause significant delays in view rendering with a large 58 | # number of complex assets. 59 | config.assets.debug = true 60 | 61 | # Suppress logger output for asset requests. 62 | config.assets.quiet = true 63 | 64 | # Raises error for missing translations. 65 | # config.i18n.raise_on_missing_translations = true 66 | 67 | # Annotate rendered view with file names. 68 | # config.action_view.annotate_rendered_view_with_filenames = true 69 | 70 | # Use an evented file watcher to asynchronously detect changes in source code, 71 | # routes, locales, etc. This feature depends on the listen gem. 72 | # config.file_watcher = ActiveSupport::EventedFileUpdateChecker 73 | 74 | # Uncomment if you wish to allow Action Cable access from any origin. 75 | # config.action_cable.disable_request_forgery_protection = true 76 | end 77 | -------------------------------------------------------------------------------- /spec/dummy/config/environments/production.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/integer/time" 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # Code is not reloaded between requests. 7 | config.cache_classes = true 8 | 9 | # Eager load code on boot. This eager loads most of Rails and 10 | # your application in memory, allowing both threaded web servers 11 | # and those relying on copy on write to perform better. 12 | # Rake tasks automatically ignore this option for performance. 13 | config.eager_load = true 14 | 15 | # Full error reports are disabled and caching is turned on. 16 | config.consider_all_requests_local = false 17 | config.action_controller.perform_caching = true 18 | 19 | # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] 20 | # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). 21 | # config.require_master_key = true 22 | 23 | # Disable serving static files from the `/public` folder by default since 24 | # Apache or NGINX already handles this. 25 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? 26 | 27 | # Compress CSS using a preprocessor. 28 | # config.assets.css_compressor = :sass 29 | 30 | # Do not fallback to assets pipeline if a precompiled asset is missed. 31 | config.assets.compile = false 32 | 33 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 34 | # config.asset_host = 'http://assets.example.com' 35 | 36 | # Specifies the header that your server uses for sending files. 37 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 38 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 39 | 40 | # Store uploaded files on the local file system (see config/storage.yml for options). 41 | config.active_storage.service = :local 42 | 43 | # Mount Action Cable outside main process or domain. 44 | # config.action_cable.mount_path = nil 45 | # config.action_cable.url = 'wss://example.com/cable' 46 | # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] 47 | 48 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 49 | # config.force_ssl = true 50 | 51 | # Include generic and useful information about system operation, but avoid logging too much 52 | # information to avoid inadvertent exposure of personally identifiable information (PII). 53 | config.log_level = :info 54 | 55 | # Prepend all log lines with the following tags. 56 | config.log_tags = [ :request_id ] 57 | 58 | # Use a different cache store in production. 59 | # config.cache_store = :mem_cache_store 60 | 61 | # Use a real queuing backend for Active Job (and separate queues per environment). 62 | # config.active_job.queue_adapter = :resque 63 | # config.active_job.queue_name_prefix = "dummy_production" 64 | 65 | config.action_mailer.perform_caching = false 66 | 67 | # Ignore bad email addresses and do not raise email delivery errors. 68 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 69 | # config.action_mailer.raise_delivery_errors = false 70 | 71 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 72 | # the I18n.default_locale when a translation cannot be found). 73 | config.i18n.fallbacks = true 74 | 75 | # Send deprecation notices to registered listeners. 76 | config.active_support.deprecation = :notify 77 | 78 | # Log disallowed deprecations. 79 | config.active_support.disallowed_deprecation = :log 80 | 81 | # Tell Active Support which deprecation messages to disallow. 82 | config.active_support.disallowed_deprecation_warnings = [] 83 | 84 | # Use default logging formatter so that PID and timestamp are not suppressed. 85 | config.log_formatter = ::Logger::Formatter.new 86 | 87 | # Use a different logger for distributed setups. 88 | # require "syslog/logger" 89 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 90 | 91 | if ENV["RAILS_LOG_TO_STDOUT"].present? 92 | logger = ActiveSupport::Logger.new(STDOUT) 93 | logger.formatter = config.log_formatter 94 | config.logger = ActiveSupport::TaggedLogging.new(logger) 95 | end 96 | 97 | # Do not dump schema after migrations. 98 | config.active_record.dump_schema_after_migration = false 99 | 100 | # Inserts middleware to perform automatic connection switching. 101 | # The `database_selector` hash is used to pass options to the DatabaseSelector 102 | # middleware. The `delay` is used to determine how long to wait after a write 103 | # to send a subsequent read to the primary. 104 | # 105 | # The `database_resolver` class is used by the middleware to determine which 106 | # database is appropriate to use based on the time delay. 107 | # 108 | # The `database_resolver_context` class is used by the middleware to set 109 | # timestamps for the last write to the primary. The resolver uses the context 110 | # class timestamps to determine how long to wait before reading from the 111 | # replica. 112 | # 113 | # By default Rails will store a last write timestamp in the session. The 114 | # DatabaseSelector middleware is designed as such you can define your own 115 | # strategy for connection switching and pass that into the middleware through 116 | # these configuration options. 117 | # config.active_record.database_selector = { delay: 2.seconds } 118 | # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver 119 | # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session 120 | end 121 | -------------------------------------------------------------------------------- /spec/dummy/config/environments/test.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/integer/time" 2 | 3 | # The test environment is used exclusively to run your application's 4 | # test suite. You never need to work with it otherwise. Remember that 5 | # your test database is "scratch space" for the test suite and is wiped 6 | # and recreated between test runs. Don't rely on the data there! 7 | 8 | Rails.application.configure do 9 | # Settings specified here will take precedence over those in config/application.rb. 10 | 11 | config.cache_classes = true 12 | 13 | # Do not eager load code on boot. This avoids loading your whole application 14 | # just for the purpose of running a single test. If you are using a tool that 15 | # preloads Rails for running tests, you may have to set it to true. 16 | config.eager_load = false 17 | 18 | # Configure public file server for tests with Cache-Control for performance. 19 | config.public_file_server.enabled = true 20 | config.public_file_server.headers = { 21 | 'Cache-Control' => "public, max-age=#{1.hour.to_i}" 22 | } 23 | 24 | # Show full error reports and disable caching. 25 | config.consider_all_requests_local = true 26 | config.action_controller.perform_caching = false 27 | config.cache_store = :null_store 28 | 29 | # Raise exceptions instead of rendering exception templates. 30 | config.action_dispatch.show_exceptions = false 31 | 32 | # Disable request forgery protection in test environment. 33 | config.action_controller.allow_forgery_protection = false 34 | 35 | # Store uploaded files on the local file system in a temporary directory. 36 | config.active_storage.service = :test 37 | 38 | config.action_mailer.perform_caching = false 39 | 40 | # Tell Action Mailer not to deliver emails to the real world. 41 | # The :test delivery method accumulates sent emails in the 42 | # ActionMailer::Base.deliveries array. 43 | config.action_mailer.delivery_method = :test 44 | 45 | # Print deprecation notices to the stderr. 46 | config.active_support.deprecation = :stderr 47 | 48 | # Raise exceptions for disallowed deprecations. 49 | config.active_support.disallowed_deprecation = :raise 50 | 51 | # Tell Active Support which deprecation messages to disallow. 52 | config.active_support.disallowed_deprecation_warnings = [] 53 | 54 | # Raises error for missing translations. 55 | # config.i18n.raise_on_missing_translations = true 56 | 57 | # Annotate rendered view with file names. 58 | # config.action_view.annotate_rendered_view_with_filenames = true 59 | end 60 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/active_model_serializers.rb: -------------------------------------------------------------------------------- 1 | ActiveModelSerializers.config.adapter = :json 2 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/api_pagination.rb: -------------------------------------------------------------------------------- 1 | ApiPagination.configure do |config| 2 | # If you have more than one gem included, you can choose a paginator. 3 | config.paginator = :kaminari 4 | 5 | # By default, this is set to 'Total' 6 | config.total_header = 'X-Total' 7 | 8 | # By default, this is set to 'Per-Page' 9 | config.per_page_header = 'X-Per-Page' 10 | 11 | # Optional: set this to add a header with the current page number. 12 | config.page_header = 'X-Page' 13 | 14 | # Optional: set this to add other response format. Useful with tools that define :jsonapi format 15 | # config.response_formats = [:json, :xml, :jsonapi] 16 | config.response_formats = [:jsonapi] 17 | 18 | # Optional: what parameter should be used to set the page option 19 | config.page_param do |params| 20 | params[:page][:number] if params[:page].is_a?(ActionController::Parameters) 21 | end 22 | 23 | # Optional: what parameter should be used to set the per page option 24 | config.per_page_param do |params| 25 | params[:page][:size] if params[:page].is_a?(ActionController::Parameters) 26 | end 27 | 28 | # Optional: Include the total and last_page link header 29 | # By default, this is set to true 30 | # Note: When using kaminari, this prevents the count call to the database 31 | config.include_total = true 32 | end 33 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/application_controller_renderer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # ActiveSupport::Reloader.to_prepare do 4 | # ApplicationController.renderer.defaults.merge!( 5 | # http_host: 'example.org', 6 | # https: false 7 | # ) 8 | # end 9 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/assets.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Version of your assets, change this if you want to expire all your assets. 4 | Rails.application.config.assets.version = '1.0' 5 | 6 | # Add additional assets to the asset load path. 7 | # Rails.application.config.assets.paths << Emoji.images_path 8 | 9 | # Precompile additional assets. 10 | # application.js, application.css, and all non-JS/CSS in the app/assets 11 | # folder are already added. 12 | # Rails.application.config.assets.precompile += %w( admin.js admin.css ) 13 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| /my_noisy_library/.match?(line) } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code 7 | # by setting BACKTRACE=1 before calling your invocation, like "BACKTRACE=1 ./bin/rails runner 'MyClass.perform'". 8 | Rails.backtrace_cleaner.remove_silencers! if ENV["BACKTRACE"] 9 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/content_security_policy.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Define an application-wide content security policy 4 | # For further information see the following documentation 5 | # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy 6 | 7 | # Rails.application.config.content_security_policy do |policy| 8 | # policy.default_src :self, :https 9 | # policy.font_src :self, :https, :data 10 | # policy.img_src :self, :https, :data 11 | # policy.object_src :none 12 | # policy.script_src :self, :https 13 | # policy.style_src :self, :https 14 | 15 | # # Specify URI for violation reports 16 | # # policy.report_uri "/csp-violation-report-endpoint" 17 | # end 18 | 19 | # If you are using UJS then enable automatic nonce generation 20 | # Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) } 21 | 22 | # Set the nonce only to specific directives 23 | # Rails.application.config.content_security_policy_nonce_directives = %w(script-src) 24 | 25 | # Report CSP violations to a specified URI 26 | # For further information see the following documentation: 27 | # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only 28 | # Rails.application.config.content_security_policy_report_only = true 29 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/cookies_serializer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Specify a serializer for the signed and encrypted cookie jars. 4 | # Valid options are :json, :marshal, and :hybrid. 5 | Rails.application.config.action_dispatch.cookies_serializer = :json 6 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure sensitive parameters which will be filtered from the log file. 4 | Rails.application.config.filter_parameters += [ 5 | :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn 6 | ] 7 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format. Inflections 4 | # are locale specific, and you may define rules for as many different 5 | # locales as you wish. All of these examples are active by default: 6 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 7 | # inflect.plural /^(ox)$/i, '\1en' 8 | # inflect.singular /^(ox)en/i, '\1' 9 | # inflect.irregular 'person', 'people' 10 | # inflect.uncountable %w( fish sheep ) 11 | # end 12 | 13 | # These inflection rules are supported but not enabled by default: 14 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 15 | # inflect.acronym 'RESTful' 16 | # end 17 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new mime types for use in respond_to blocks: 4 | # Mime::Type.register "text/richtext", :rtf 5 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/permissions_policy.rb: -------------------------------------------------------------------------------- 1 | # Define an application-wide HTTP permissions policy. For further 2 | # information see https://developers.google.com/web/updates/2018/06/feature-policy 3 | # 4 | # Rails.application.config.permissions_policy do |f| 5 | # f.camera :none 6 | # f.gyroscope :none 7 | # f.microphone :none 8 | # f.usb :none 9 | # f.fullscreen :self 10 | # f.payment :self, "https://secure.example.com" 11 | # end 12 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # This file contains settings for ActionController::ParamsWrapper which 4 | # is enabled by default. 5 | 6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 7 | ActiveSupport.on_load(:action_controller) do 8 | wrap_parameters format: [:json] 9 | end 10 | 11 | # To enable root element in JSON for ActiveRecord objects. 12 | # ActiveSupport.on_load(:active_record) do 13 | # self.include_root_in_json = true 14 | # end 15 | -------------------------------------------------------------------------------- /spec/dummy/config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Files in the config/locales directory are used for internationalization 2 | # and are automatically loaded by Rails. If you want to use locales other 3 | # than English, add the necessary files in this directory. 4 | # 5 | # To use the locales, use `I18n.t`: 6 | # 7 | # I18n.t 'hello' 8 | # 9 | # In views, this is aliased to just `t`: 10 | # 11 | # <%= t('hello') %> 12 | # 13 | # To use a different locale, set it with `I18n.locale`: 14 | # 15 | # I18n.locale = :es 16 | # 17 | # This would use the information in config/locales/es.yml. 18 | # 19 | # The following keys must be escaped otherwise they will not be retrieved by 20 | # the default I18n backend: 21 | # 22 | # true, false, on, off, yes, no 23 | # 24 | # Instead, surround them with single quotes. 25 | # 26 | # en: 27 | # 'true': 'foo' 28 | # 29 | # To learn more, please read the Rails Internationalization guide 30 | # available at https://guides.rubyonrails.org/i18n.html. 31 | 32 | en: 33 | hello: "Hello world" 34 | -------------------------------------------------------------------------------- /spec/dummy/config/puma.rb: -------------------------------------------------------------------------------- 1 | # Puma can serve each request in a thread from an internal thread pool. 2 | # The `threads` method setting takes two numbers: a minimum and maximum. 3 | # Any libraries that use thread pools should be configured to match 4 | # the maximum value specified for Puma. Default is set to 5 threads for minimum 5 | # and maximum; this matches the default thread size of Active Record. 6 | # 7 | max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } 8 | min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } 9 | threads min_threads_count, max_threads_count 10 | 11 | # Specifies the `worker_timeout` threshold that Puma will use to wait before 12 | # terminating a worker in development environments. 13 | # 14 | worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development" 15 | 16 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000. 17 | # 18 | port ENV.fetch("PORT") { 3000 } 19 | 20 | # Specifies the `environment` that Puma will run in. 21 | # 22 | environment ENV.fetch("RAILS_ENV") { "development" } 23 | 24 | # Specifies the `pidfile` that Puma will use. 25 | pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } 26 | 27 | # Specifies the number of `workers` to boot in clustered mode. 28 | # Workers are forked web server processes. If using threads and workers together 29 | # the concurrency of the application would be max `threads` * `workers`. 30 | # Workers do not work on JRuby or Windows (both of which do not support 31 | # processes). 32 | # 33 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 } 34 | 35 | # Use the `preload_app!` method when specifying a `workers` number. 36 | # This directive tells Puma to first boot the application and load code 37 | # before forking the application. This takes advantage of Copy On Write 38 | # process behavior so workers use less memory. 39 | # 40 | # preload_app! 41 | 42 | # Allow puma to be restarted by `rails restart` command. 43 | plugin :tmp_restart 44 | -------------------------------------------------------------------------------- /spec/dummy/config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | namespace :api, defaults: { format: :json } do 3 | namespace :internal do 4 | resources :blogs 5 | end 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /spec/dummy/config/storage.yml: -------------------------------------------------------------------------------- 1 | test: 2 | service: Disk 3 | root: <%= Rails.root.join("tmp/storage") %> 4 | 5 | local: 6 | service: Disk 7 | root: <%= Rails.root.join("storage") %> 8 | 9 | # Use rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) 10 | # amazon: 11 | # service: S3 12 | # access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> 13 | # secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> 14 | # region: us-east-1 15 | # bucket: your_own_bucket 16 | 17 | # Remember not to checkin your GCS keyfile to a repository 18 | # google: 19 | # service: GCS 20 | # project: your_project 21 | # credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> 22 | # bucket: your_own_bucket 23 | 24 | # Use rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) 25 | # microsoft: 26 | # service: AzureStorage 27 | # storage_account_name: your_account_name 28 | # storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> 29 | # container: your_container_name 30 | 31 | # mirror: 32 | # service: Mirror 33 | # primary: local 34 | # mirrors: [ amazon, google, microsoft ] 35 | -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20190322205209_create_blogs.rb: -------------------------------------------------------------------------------- 1 | class CreateBlogs < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :blogs do |t| 4 | t.string :title 5 | t.text :body 6 | 7 | t.timestamps 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20200215225917_create_users.rb: -------------------------------------------------------------------------------- 1 | class CreateUsers < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :users do |t| 4 | t.string :email 5 | 6 | t.timestamps 7 | end 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20200227150449_create_portfolios.rb: -------------------------------------------------------------------------------- 1 | class CreatePortfolios < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :portfolios do |t| 4 | t.string :name 5 | t.references :user, foreign_key: true 6 | 7 | t.timestamps 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20200227150548_add_portfolio_id_blogs.rb: -------------------------------------------------------------------------------- 1 | class AddPortfolioIdBlogs < ActiveRecord::Migration[5.2] 2 | def change 3 | add_reference :blogs, :portfolio, foreign_key: true, index: true 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /spec/dummy/db/schema.rb: -------------------------------------------------------------------------------- 1 | # This file is auto-generated from the current state of the database. Instead 2 | # of editing this file, please use the migrations feature of Active Record to 3 | # incrementally modify your database, and then regenerate this schema definition. 4 | # 5 | # Note that this schema.rb definition is the authoritative source for your 6 | # database schema. If you need to create the application database on another 7 | # system, you should be using db:schema:load, not running all the migrations 8 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 9 | # you'll amass, the slower it'll run and the greater likelihood for issues). 10 | # 11 | # It's strongly recommended that you check this file into your version control system. 12 | 13 | ActiveRecord::Schema.define(version: 2020_02_27_150548) do 14 | 15 | create_table "blogs", force: :cascade do |t| 16 | t.string "title" 17 | t.text "body" 18 | t.datetime "created_at", null: false 19 | t.datetime "updated_at", null: false 20 | t.integer "portfolio_id" 21 | t.index ["portfolio_id"], name: "index_blogs_on_portfolio_id" 22 | end 23 | 24 | create_table "portfolios", force: :cascade do |t| 25 | t.string "name" 26 | t.integer "user_id" 27 | t.datetime "created_at", null: false 28 | t.datetime "updated_at", null: false 29 | t.index ["user_id"], name: "index_portfolios_on_user_id" 30 | end 31 | 32 | create_table "users", force: :cascade do |t| 33 | t.string "email" 34 | t.datetime "created_at", null: false 35 | t.datetime "updated_at", null: false 36 | end 37 | 38 | end 39 | -------------------------------------------------------------------------------- /spec/dummy/lib/assets/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/platanus/power_api/fc84727c8772199266af4d66f88b2bdd6dd0c4f4/spec/dummy/lib/assets/.keep -------------------------------------------------------------------------------- /spec/dummy/log/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/platanus/power_api/fc84727c8772199266af4d66f88b2bdd6dd0c4f4/spec/dummy/log/.keep -------------------------------------------------------------------------------- /spec/dummy/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "dummy", 3 | "private": true, 4 | "dependencies": {} 5 | } 6 | -------------------------------------------------------------------------------- /spec/dummy/public/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The page you were looking for doesn't exist (404) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The page you were looking for doesn't exist.

62 |

You may have mistyped the address or the page may have moved.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /spec/dummy/public/422.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The change you wanted was rejected (422) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The change you wanted was rejected.

62 |

Maybe you tried to change something you didn't have access to.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /spec/dummy/public/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | We're sorry, but something went wrong (500) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

We're sorry, but something went wrong.

62 |
63 |

If you are the application owner check the logs for more information.

64 |
65 | 66 | 67 | -------------------------------------------------------------------------------- /spec/dummy/public/apple-touch-icon-precomposed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/platanus/power_api/fc84727c8772199266af4d66f88b2bdd6dd0c4f4/spec/dummy/public/apple-touch-icon-precomposed.png -------------------------------------------------------------------------------- /spec/dummy/public/apple-touch-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/platanus/power_api/fc84727c8772199266af4d66f88b2bdd6dd0c4f4/spec/dummy/public/apple-touch-icon.png -------------------------------------------------------------------------------- /spec/dummy/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/platanus/power_api/fc84727c8772199266af4d66f88b2bdd6dd0c4f4/spec/dummy/public/favicon.ico -------------------------------------------------------------------------------- /spec/dummy/spec/assets/image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/platanus/power_api/fc84727c8772199266af4d66f88b2bdd6dd0c4f4/spec/dummy/spec/assets/image.png -------------------------------------------------------------------------------- /spec/dummy/spec/assets/video.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/platanus/power_api/fc84727c8772199266af4d66f88b2bdd6dd0c4f4/spec/dummy/spec/assets/video.mp4 -------------------------------------------------------------------------------- /spec/dummy/spec/factories/blogs.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :blog do 3 | portfolio 4 | title { "MyString" } 5 | body { "MyText" } 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /spec/dummy/spec/factories/portfolios.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :portfolio do 3 | name { "MyString" } 4 | user 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /spec/dummy/spec/factories/users.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :user do 3 | email { "leandro@platan.us" } 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /spec/dummy/spec/helpers/power_api/application_helper_spec.rb: -------------------------------------------------------------------------------- 1 | require "spec_helper" 2 | 3 | describe PowerApi::ApplicationHelper do 4 | describe "#serialize_resource" do 5 | let(:resource) do 6 | build( 7 | :blog, 8 | id: 1, 9 | title: "T", 10 | portfolio_id: 2, 11 | body: "B", 12 | created_at: "2022-01-28T20:30:00.000Z", 13 | updated_at: "2022-01-28T20:40:00.000Z" 14 | ) 15 | end 16 | 17 | let(:options) { {} } 18 | 19 | def data 20 | helper.serialize_resource(resource, options) 21 | end 22 | 23 | let(:expected_serialized_data) do 24 | <<~DATA.strip 25 | {\"id\":1,\"title\":\"T\",\"body\":\"B\",\"createdAt\":\"2022-01-28T20:30:00.000Z\",\"updatedAt\":\"2022-01-28T20:40:00.000Z\",\"portfolioId\":2} 26 | DATA 27 | end 28 | 29 | it { expect(data).to eq(expected_serialized_data) } 30 | 31 | context "with fields option" do 32 | let(:options) do 33 | { 34 | fields: [:id, :body] 35 | } 36 | end 37 | 38 | let(:expected_serialized_data) do 39 | <<~DATA.strip 40 | {\"id\":1,\"body\":\"B\"} 41 | DATA 42 | end 43 | 44 | it { expect(data).to eq(expected_serialized_data) } 45 | end 46 | 47 | context "with key_transform option" do 48 | let(:options) do 49 | { 50 | key_transform: :unaltered 51 | } 52 | end 53 | 54 | let(:expected_serialized_data) do 55 | <<~DATA.strip 56 | {\"id\":1,\"title\":\"T\",\"body\":\"B\",\"created_at\":\"2022-01-28T20:30:00.000Z\",\"updated_at\":\"2022-01-28T20:40:00.000Z\",\"portfolio_id\":2} 57 | DATA 58 | end 59 | 60 | it { expect(data).to eq(expected_serialized_data) } 61 | end 62 | 63 | context "with include_root option" do 64 | let(:options) do 65 | { 66 | include_root: true 67 | } 68 | end 69 | 70 | let(:expected_serialized_data) do 71 | <<~DATA.strip 72 | {"blog":{"id":1,"title":"T","body":"B","createdAt":"2022-01-28T20:30:00.000Z","updatedAt":"2022-01-28T20:40:00.000Z","portfolioId":2}} 73 | DATA 74 | end 75 | 76 | it { expect(data).to eq(expected_serialized_data) } 77 | end 78 | 79 | context "with collection resource" do 80 | let(:options) do 81 | { 82 | include_root: false, 83 | fields: [:body] 84 | } 85 | end 86 | 87 | let(:resource) do 88 | create_list(:blog, 2) 89 | end 90 | 91 | let(:expected_serialized_data) do 92 | <<~DATA.strip 93 | [{\"body\":\"MyText\"},{\"body\":\"MyText\"}] 94 | DATA 95 | end 96 | 97 | it { expect(data).to eq(expected_serialized_data) } 98 | end 99 | 100 | context "with nil resource" do 101 | let(:resource) { nil } 102 | let(:expected_serialized_data) { "null" } 103 | 104 | it { expect(data).to eq(expected_serialized_data) } 105 | end 106 | 107 | context "with invalid resource" do 108 | let(:resource) do 109 | { invalid: "resource" } 110 | end 111 | 112 | it { expect { data }.to raise_error(PowerApi::InvalidSerializableResource, /Invalid Hash/) } 113 | end 114 | 115 | context "with hash output_format" do 116 | let(:options) do 117 | { 118 | output_format: :hash 119 | } 120 | end 121 | 122 | let(:expected_serialized_data) do 123 | { 124 | body: "B", 125 | created_at: "2022-01-28 20:30:00.000000000 +0000", 126 | id: 1, 127 | portfolio_id: 2, 128 | title: "T", 129 | updated_at: "2022-01-28 20:40:00.000000000 +0000" 130 | } 131 | end 132 | 133 | it { expect(data).to eq(expected_serialized_data) } 134 | 135 | context "with key_transform option" do 136 | before { options[:key_transform] = :camel_lower } 137 | 138 | it { expect(data).to eq(expected_serialized_data) } 139 | end 140 | 141 | context "with nil resource" do 142 | let(:resource) { nil } 143 | let(:expected_serialized_data) { {} } 144 | 145 | it { expect(data).to eq(expected_serialized_data) } 146 | end 147 | end 148 | 149 | context "with invalid output option" do 150 | let(:options) do 151 | { output_format: "invalid" } 152 | end 153 | 154 | it { expect { data }.to raise_error(PowerApi::InvalidSerializerOutputFormat, /:json, :hash/) } 155 | end 156 | 157 | context "with meta option" do 158 | let(:options) do 159 | { 160 | meta: { hola: "platanus" } 161 | } 162 | end 163 | 164 | let(:expected_serialized_data) do 165 | <<~DATA.strip 166 | {\"id\":1,\"title\":\"T\",\"body\":\"B\",\"createdAt\":\"2022-01-28T20:30:00.000Z\",\"updatedAt\":\"2022-01-28T20:40:00.000Z\",\"portfolioId\":2} 167 | DATA 168 | end 169 | 170 | it { expect(data).to eq(expected_serialized_data) } 171 | 172 | context "with include_root option" do 173 | before { options[:include_root] = true } 174 | 175 | let(:expected_serialized_data) do 176 | <<~DATA.strip 177 | {\"blog\":{\"id\":1,\"title\":\"T\",\"body\":\"B\",\"createdAt\":\"2022-01-28T20:30:00.000Z\",\"updatedAt\":\"2022-01-28T20:40:00.000Z\",\"portfolioId\":2},\"meta\":{\"hola\":\"platanus\"}} 178 | DATA 179 | end 180 | 181 | it { expect(data).to eq(expected_serialized_data) } 182 | end 183 | end 184 | end 185 | end 186 | -------------------------------------------------------------------------------- /spec/dummy/spec/lib/power_api/generator_helper/ams_helper_spec.rb: -------------------------------------------------------------------------------- 1 | RSpec.describe PowerApi::GeneratorHelper::AmsHelper, type: :generator do 2 | describe "#ams_initializer_path" do 3 | let(:expected_path) { "config/initializers/active_model_serializers.rb" } 4 | 5 | def perform 6 | generators_helper.ams_initializer_path 7 | end 8 | 9 | it { expect(perform).to eq(expected_path) } 10 | end 11 | 12 | describe "#ams_serializers_path" do 13 | let(:expected_path) do 14 | "app/serializers/api/exposed/v1/.gitkeep" 15 | end 16 | 17 | def perform 18 | subject.ams_serializers_path 19 | end 20 | 21 | it { expect(perform).to eq(expected_path) } 22 | 23 | context "with another version" do 24 | let(:version_number) { "2" } 25 | 26 | let(:expected_path) do 27 | "app/serializers/api/exposed/v2/.gitkeep" 28 | end 29 | 30 | it { expect(perform).to eq(expected_path) } 31 | end 32 | 33 | context "with no version" do 34 | let(:version_number) { "" } 35 | 36 | let(:expected_path) do 37 | "app/serializers/api/internal/.gitkeep" 38 | end 39 | 40 | it { expect(perform).to eq(expected_path) } 41 | end 42 | end 43 | 44 | describe "#ams_serializer_path" do 45 | let(:expected_path) { "app/serializers/api/exposed/v1/blog_serializer.rb" } 46 | 47 | def perform 48 | generators_helper.ams_serializer_path 49 | end 50 | 51 | it { expect(perform).to eq(expected_path) } 52 | 53 | context "with no version" do 54 | let(:version_number) { nil } 55 | 56 | let(:expected_path) do 57 | "app/serializers/api/internal/blog_serializer.rb" 58 | end 59 | 60 | it { expect(perform).to eq(expected_path) } 61 | end 62 | end 63 | 64 | describe "ams_initializer_tpl" do 65 | let(:template) do 66 | <<~INITIALIZER 67 | ActiveModelSerializers.config.adapter = :json 68 | INITIALIZER 69 | end 70 | 71 | def perform 72 | generators_helper.ams_initializer_tpl 73 | end 74 | 75 | it { expect(perform).to eq(template) } 76 | end 77 | 78 | describe "ams_serializer_tpl" do 79 | let(:template) do 80 | <<~SERIALIZER 81 | class Api::Exposed::V1::BlogSerializer < ActiveModel::Serializer 82 | type :blog 83 | 84 | attributes( 85 | :id, 86 | :title, 87 | :body, 88 | :created_at, 89 | :updated_at, 90 | :portfolio_id 91 | ) 92 | end 93 | SERIALIZER 94 | end 95 | 96 | def perform 97 | generators_helper.ams_serializer_tpl 98 | end 99 | 100 | it { expect(perform).to eq(template) } 101 | 102 | context "with no version" do 103 | let(:version_number) { nil } 104 | 105 | let(:template) do 106 | <<~SERIALIZER 107 | class Api::Internal::BlogSerializer < ActiveModel::Serializer 108 | type :blog 109 | 110 | attributes( 111 | :id, 112 | :title, 113 | :body, 114 | :created_at, 115 | :updated_at, 116 | :portfolio_id 117 | ) 118 | end 119 | SERIALIZER 120 | end 121 | 122 | it { expect(perform).to eq(template) } 123 | end 124 | end 125 | end 126 | -------------------------------------------------------------------------------- /spec/dummy/spec/lib/power_api/generator_helper/api_helper_spec.rb: -------------------------------------------------------------------------------- 1 | RSpec.describe PowerApi::GeneratorHelper::ApiHelper, type: :generator do 2 | describe "#version_number" do 3 | def perform 4 | generators_helper.version_number 5 | end 6 | 7 | it { expect(perform).to eq(1) } 8 | end 9 | 10 | describe "version_number=" do 11 | context "with invalid version number" do 12 | let(:version_number) { "A" } 13 | 14 | it { expect { generators_helper }.to raise_error("invalid version number") } 15 | end 16 | 17 | context "with zero version number" do 18 | let(:version_number) { 0 } 19 | 20 | it { expect { generators_helper }.to raise_error("invalid version number") } 21 | end 22 | 23 | context "with nil version number" do 24 | let(:version_number) { nil } 25 | 26 | it { expect { generators_helper }.not_to raise_error } 27 | end 28 | 29 | context "with nil blank number" do 30 | let(:version_number) { "" } 31 | 32 | it { expect { generators_helper }.not_to raise_error } 33 | end 34 | 35 | context "with negative version number" do 36 | let(:version_number) { -1 } 37 | 38 | it { expect { generators_helper }.to raise_error("invalid version number") } 39 | end 40 | end 41 | 42 | describe "#first_version?" do 43 | def perform 44 | generators_helper.first_version? 45 | end 46 | 47 | it { expect(perform).to eq(true) } 48 | 49 | context "when version in not first version" do 50 | let(:version_number) { "2" } 51 | 52 | it { expect(perform).to eq(false) } 53 | end 54 | end 55 | 56 | describe "#versioned_api?" do 57 | def perform 58 | generators_helper.versioned_api? 59 | end 60 | 61 | it { expect(perform).to eq(true) } 62 | 63 | context "when version in not first version" do 64 | let(:version_number) { "2" } 65 | 66 | it { expect(perform).to eq(true) } 67 | end 68 | 69 | context "when nil version" do 70 | let(:version_number) { nil } 71 | 72 | it { expect(perform).to eq(false) } 73 | end 74 | end 75 | 76 | describe "#api_file_path" do 77 | def perform 78 | generators_helper.api_file_path 79 | end 80 | 81 | it { expect(perform).to eq("api/exposed/v1") } 82 | 83 | context "when version in not first version" do 84 | let(:version_number) { "2" } 85 | 86 | it { expect(perform).to eq("api/exposed/v2") } 87 | end 88 | 89 | context "when nil version" do 90 | let(:version_number) { nil } 91 | 92 | it { expect(perform).to eq("api/internal") } 93 | end 94 | end 95 | 96 | describe "#api_class" do 97 | def perform 98 | generators_helper.api_class 99 | end 100 | 101 | it { expect(perform).to eq("Api::Exposed::V1") } 102 | 103 | context "when version in not first version" do 104 | let(:version_number) { "2" } 105 | 106 | it { expect(perform).to eq("Api::Exposed::V2") } 107 | end 108 | 109 | context "when nil version" do 110 | let(:version_number) { nil } 111 | 112 | it { expect(perform).to eq("Api::Internal") } 113 | end 114 | end 115 | end 116 | -------------------------------------------------------------------------------- /spec/dummy/spec/lib/power_api/generator_helper/controller_actions_helper_spec.rb: -------------------------------------------------------------------------------- 1 | RSpec.describe PowerApi::GeneratorHelper::ControllerActionsHelper, type: :generator do 2 | describe '#controller_actions=' do 3 | context 'when arg is nil' do 4 | before { generators_helper.controller_actions = nil } 5 | 6 | it do 7 | expect(generators_helper.controller_actions).to( 8 | match_array(generators_helper.class::PERMITTED_ACTIONS) 9 | ) 10 | end 11 | end 12 | 13 | context 'when arg is empty array' do 14 | before { generators_helper.controller_actions = [] } 15 | 16 | it do 17 | expect(generators_helper.controller_actions).to( 18 | match_array(generators_helper.class::PERMITTED_ACTIONS) 19 | ) 20 | end 21 | end 22 | 23 | context 'when including not permitted actions' do 24 | before { generators_helper.controller_actions = ['index', 'clone'] } 25 | 26 | it 'ignores them' do 27 | expect(generators_helper.controller_actions).to match_array(['index']) 28 | end 29 | end 30 | 31 | context 'when including only permitted actions' do 32 | let(:actions) { ['index', 'show'] } 33 | 34 | before { generators_helper.controller_actions = actions } 35 | 36 | it 'includes them all' do 37 | expect(generators_helper.controller_actions).to match_array(actions) 38 | end 39 | end 40 | end 41 | 42 | describe 'index?' do 43 | context 'when including index action' do 44 | before { generators_helper.controller_actions = ['index'] } 45 | 46 | it { expect(generators_helper.index?).to be(true) } 47 | end 48 | 49 | context 'when not including index action' do 50 | before { generators_helper.controller_actions = ['show'] } 51 | 52 | it { expect(generators_helper.index?).to be(false) } 53 | end 54 | end 55 | 56 | describe 'show?' do 57 | context 'when including show action' do 58 | before { generators_helper.controller_actions = ['show'] } 59 | 60 | it { expect(generators_helper.show?).to be(true) } 61 | end 62 | 63 | context 'when not including show action' do 64 | before { generators_helper.controller_actions = ['index'] } 65 | 66 | it { expect(generators_helper.show?).to be(false) } 67 | end 68 | end 69 | 70 | describe 'update?' do 71 | context 'when including update action' do 72 | before { generators_helper.controller_actions = ['update'] } 73 | 74 | it { expect(generators_helper.update?).to be(true) } 75 | end 76 | 77 | context 'when not including update action' do 78 | before { generators_helper.controller_actions = ['show'] } 79 | 80 | it { expect(generators_helper.update?).to be(false) } 81 | end 82 | end 83 | 84 | describe 'create?' do 85 | context 'when including create action' do 86 | before { generators_helper.controller_actions = ['create'] } 87 | 88 | it { expect(generators_helper.create?).to be(true) } 89 | end 90 | 91 | context 'when not including create action' do 92 | before { generators_helper.controller_actions = ['show'] } 93 | 94 | it { expect(generators_helper.create?).to be(false) } 95 | end 96 | end 97 | 98 | describe 'destroy?' do 99 | context 'when including destroy action' do 100 | before { generators_helper.controller_actions = ['destroy'] } 101 | 102 | it { expect(generators_helper.destroy?).to be(true) } 103 | end 104 | 105 | context 'when not including destroy action' do 106 | before { generators_helper.controller_actions = ['show'] } 107 | 108 | it { expect(generators_helper.destroy?).to be(false) } 109 | end 110 | end 111 | 112 | describe 'resource_actions?' do 113 | context 'when including show action' do 114 | before { generators_helper.controller_actions = ['show'] } 115 | 116 | it { expect(generators_helper.resource_actions?).to be(true) } 117 | end 118 | 119 | context 'when including update action' do 120 | before { generators_helper.controller_actions = ['update'] } 121 | 122 | it { expect(generators_helper.resource_actions?).to be(true) } 123 | end 124 | 125 | context 'when including destroy action' do 126 | before { generators_helper.controller_actions = ['destroy'] } 127 | 128 | it { expect(generators_helper.resource_actions?).to be(true) } 129 | end 130 | 131 | context 'when not including show, update or destroy actions' do 132 | before { generators_helper.controller_actions = ['index', 'create'] } 133 | 134 | it { expect(generators_helper.resource_actions?).to be(false) } 135 | end 136 | end 137 | 138 | describe 'collection_actions?' do 139 | context 'when including index action' do 140 | before { generators_helper.controller_actions = ['index'] } 141 | 142 | it { expect(generators_helper.collection_actions?).to be(true) } 143 | end 144 | 145 | context 'when including create action' do 146 | before { generators_helper.controller_actions = ['create'] } 147 | 148 | it { expect(generators_helper.collection_actions?).to be(true) } 149 | end 150 | 151 | context 'when not including index or create actions' do 152 | before { generators_helper.controller_actions = ['show', 'update', 'destroy'] } 153 | 154 | it { expect(generators_helper.collection_actions?).to be(false) } 155 | end 156 | end 157 | 158 | describe 'update_or_create?' do 159 | context 'when including update action' do 160 | before { generators_helper.controller_actions = ['update'] } 161 | 162 | it { expect(generators_helper.update_or_create?).to be(true) } 163 | end 164 | 165 | context 'when including create action' do 166 | before { generators_helper.controller_actions = ['create'] } 167 | 168 | it { expect(generators_helper.update_or_create?).to be(true) } 169 | end 170 | 171 | context 'when not including update or create actions' do 172 | before { generators_helper.controller_actions = ['show', 'index', 'destroy'] } 173 | 174 | it { expect(generators_helper.update_or_create?).to be(false) } 175 | end 176 | end 177 | end 178 | -------------------------------------------------------------------------------- /spec/dummy/spec/lib/power_api/generator_helper/controller_helper_spec.rb: -------------------------------------------------------------------------------- 1 | describe PowerApi::GeneratorHelper::ControllerHelper, type: :generator do 2 | describe "#api_main_base_controller_path" do 3 | let(:expected_path) { "app/controllers/api/base_controller.rb" } 4 | 5 | def perform 6 | generators_helper.api_main_base_controller_path 7 | end 8 | 9 | it { expect(perform).to eq(expected_path) } 10 | end 11 | 12 | describe "#exposed_base_controller_path" do 13 | let(:expected_path) { "app/controllers/api/exposed/base_controller.rb" } 14 | 15 | def perform 16 | generators_helper.exposed_base_controller_path 17 | end 18 | 19 | it { expect(perform).to eq(expected_path) } 20 | end 21 | 22 | describe "#internal_base_controller_path" do 23 | let(:expected_path) { "app/controllers/api/internal/base_controller.rb" } 24 | 25 | def perform 26 | generators_helper.internal_base_controller_path 27 | end 28 | 29 | it { expect(perform).to eq(expected_path) } 30 | end 31 | 32 | describe "#version_base_controller_path" do 33 | let(:expected_path) { "app/controllers/api/exposed/v1/base_controller.rb" } 34 | 35 | def perform 36 | generators_helper.version_base_controller_path 37 | end 38 | 39 | it { expect(perform).to eq(expected_path) } 40 | end 41 | 42 | describe "#resource_controller_path" do 43 | let(:expected_path) { "app/controllers/api/exposed/v1/blogs_controller.rb" } 44 | 45 | def perform 46 | generators_helper.resource_controller_path 47 | end 48 | 49 | it { expect(perform).to eq(expected_path) } 50 | 51 | context "without version" do 52 | let(:version_number) { "" } 53 | let(:expected_path) { "app/controllers/api/internal/blogs_controller.rb" } 54 | 55 | it { expect(perform).to eq(expected_path) } 56 | end 57 | end 58 | 59 | describe "#version_base_controller_path" do 60 | let(:expected_path) do 61 | "app/controllers/api/exposed/v1/base_controller.rb" 62 | end 63 | 64 | def perform 65 | generators_helper.version_base_controller_path 66 | end 67 | 68 | it { expect(perform).to eq(expected_path) } 69 | 70 | context "with another version" do 71 | let(:version_number) { "2" } 72 | 73 | let(:expected_path) do 74 | "app/controllers/api/exposed/v2/base_controller.rb" 75 | end 76 | 77 | it { expect(perform).to eq(expected_path) } 78 | end 79 | end 80 | 81 | describe "api_main_base_controller_tpl" do 82 | let(:template) do 83 | <<~CONTROLLER 84 | class Api::BaseController < PowerApi::BaseController 85 | end 86 | CONTROLLER 87 | end 88 | 89 | def perform 90 | generators_helper.api_main_base_controller_tpl 91 | end 92 | 93 | it { expect(perform).to eq(template) } 94 | end 95 | 96 | describe "exposed_base_controller_tpl" do 97 | let(:template) do 98 | <<~CONTROLLER 99 | class Api::Exposed::BaseController < Api::BaseController 100 | skip_before_action :verify_authenticity_token 101 | end 102 | CONTROLLER 103 | end 104 | 105 | def perform 106 | generators_helper.exposed_base_controller_tpl 107 | end 108 | 109 | it { expect(perform).to eq(template) } 110 | end 111 | 112 | describe "internal_base_controller_tpl" do 113 | let(:template) do 114 | <<~CONTROLLER 115 | class Api::Internal::BaseController < Api::BaseController 116 | before_action do 117 | self.namespace_for_serializer = ::Api::Internal 118 | end 119 | end 120 | CONTROLLER 121 | end 122 | 123 | def perform 124 | generators_helper.internal_base_controller_tpl 125 | end 126 | 127 | it { expect(perform).to eq(template) } 128 | end 129 | 130 | describe "resource_controller_tpl" do 131 | let(:template) do 132 | <<~CONTROLLER 133 | class Api::Exposed::V1::BlogsController < Api::Exposed::V1::BaseController 134 | def index 135 | respond_with Blog.all 136 | end 137 | def show 138 | respond_with blog 139 | end 140 | def create 141 | respond_with Blog.create!(blog_params) 142 | end 143 | def update 144 | blog.update!(blog_params) 145 | respond_with blog 146 | end 147 | def destroy 148 | respond_with blog.destroy! 149 | end 150 | private 151 | def blog 152 | @blog ||= Blog.find_by!(id: params[:id]) 153 | end 154 | def blog_params 155 | params.require(:blog).permit( 156 | :title, 157 | :body, 158 | :portfolio_id 159 | ) 160 | end 161 | end 162 | CONTROLLER 163 | end 164 | 165 | def perform 166 | generators_helper.resource_controller_tpl 167 | end 168 | 169 | it { expect(perform).to eq(template) } 170 | 171 | context "without version" do 172 | let(:version_number) { nil } 173 | let(:expected) { "class Api::Internal::BlogsController < Api::Internal::BaseController" } 174 | 175 | it { expect(perform).to include(expected) } 176 | end 177 | 178 | context "with specific attributes" do 179 | let(:resource_attributes) do 180 | [ 181 | "title", 182 | "created_at", 183 | "portfolio_id" 184 | ] 185 | end 186 | 187 | let(:expected) do 188 | ":title" 189 | end 190 | 191 | it { expect(perform).to include(expected) } 192 | end 193 | 194 | context 'with specific actions' do 195 | let(:controller_actions) do 196 | [ 197 | "show", 198 | "update", 199 | "index" 200 | ] 201 | end 202 | 203 | it { expect(perform).to include("def show\n") } 204 | it { expect(perform).to include("def update\n") } 205 | it { expect(perform).to include("def index\n") } 206 | it { expect(perform).not_to include("def destroy\n") } 207 | it { expect(perform).not_to include("def create\n") } 208 | end 209 | 210 | context 'with only collection actions' do 211 | let(:controller_actions) do 212 | [ 213 | "index", 214 | "create" 215 | ] 216 | end 217 | 218 | it { expect(perform).not_to include("def blog\n") } 219 | end 220 | 221 | context 'with some reource actions' do 222 | let(:controller_actions) do 223 | [ 224 | "index", 225 | "create", 226 | "show" 227 | ] 228 | end 229 | 230 | it { expect(perform).to include("def blog\n") } 231 | end 232 | 233 | context 'with update action' do 234 | let(:controller_actions) { ["update"] } 235 | 236 | it { expect(perform).to include("def blog_params\n") } 237 | end 238 | 239 | context 'with create action' do 240 | let(:controller_actions) { ["create"] } 241 | 242 | it { expect(perform).to include("def blog_params\n") } 243 | end 244 | 245 | context 'without update or create actions' do 246 | let(:controller_actions) do 247 | [ 248 | "index", 249 | "destroy", 250 | "show" 251 | ] 252 | end 253 | 254 | it { expect(perform).not_to include("def blog_params\n") } 255 | end 256 | 257 | context "with true use_paginator option" do 258 | let(:use_paginator) { true } 259 | let(:expected) do 260 | "respond_with paginate(Blog.all)" 261 | end 262 | 263 | it { expect(perform).to include(expected) } 264 | end 265 | 266 | context "with true allow_filters option" do 267 | let(:allow_filters) { true } 268 | let(:expected) do 269 | "respond_with filtered_collection(Blog.all)" 270 | end 271 | 272 | it { expect(perform).to include(expected) } 273 | end 274 | 275 | context "with true allow_filters and use_paginator options" do 276 | let(:allow_filters) { true } 277 | let(:use_paginator) { true } 278 | let(:expected) do 279 | "respond_with paginate(filtered_collection(Blog.all))" 280 | end 281 | 282 | it { expect(perform).to include(expected) } 283 | end 284 | 285 | context "with authenticated_resource option" do 286 | let(:authenticated_resource) { "user" } 287 | let(:template) do 288 | <<~CONTROLLER 289 | class Api::Exposed::V1::BlogsController < Api::Exposed::V1::BaseController 290 | acts_as_token_authentication_handler_for User, fallback: :exception 291 | 292 | def index 293 | respond_with Blog.all 294 | end 295 | def show 296 | respond_with blog 297 | end 298 | def create 299 | respond_with Blog.create!(blog_params) 300 | end 301 | def update 302 | blog.update!(blog_params) 303 | respond_with blog 304 | end 305 | def destroy 306 | respond_with blog.destroy! 307 | end 308 | private 309 | def blog 310 | @blog ||= Blog.find_by!(id: params[:id]) 311 | end 312 | def blog_params 313 | params.require(:blog).permit( 314 | :title, 315 | :body, 316 | :portfolio_id 317 | ) 318 | end 319 | end 320 | CONTROLLER 321 | end 322 | 323 | it { expect(perform).to eq(template) } 324 | 325 | context "without version" do 326 | let(:version_number) { nil } 327 | let(:expected) do 328 | "before_action :authenticate_user!" 329 | end 330 | 331 | it { expect(perform).to include(expected) } 332 | end 333 | end 334 | 335 | context "with owned_by_authenticated_resource and authenticated_resource" do 336 | let(:authenticated_resource) { "user" } 337 | let(:owned_by_authenticated_resource) { true } 338 | 339 | let(:template) do 340 | <<~CONTROLLER 341 | class Api::Exposed::V1::BlogsController < Api::Exposed::V1::BaseController 342 | acts_as_token_authentication_handler_for User, fallback: :exception 343 | 344 | def index 345 | respond_with blogs 346 | end 347 | def show 348 | respond_with blog 349 | end 350 | def create 351 | respond_with blogs.create!(blog_params) 352 | end 353 | def update 354 | blog.update!(blog_params) 355 | respond_with blog 356 | end 357 | def destroy 358 | respond_with blog.destroy! 359 | end 360 | private 361 | def blog 362 | @blog ||= blogs.find_by!(id: params[:id]) 363 | end 364 | def blogs 365 | @blogs ||= current_user.blogs 366 | end 367 | def blog_params 368 | params.require(:blog).permit( 369 | :title, 370 | :body, 371 | :portfolio_id 372 | ) 373 | end 374 | end 375 | CONTROLLER 376 | end 377 | 378 | it { expect(perform).to eq(template) } 379 | end 380 | 381 | context "with owned_by_authenticated_resource but authenticated_resource" do 382 | let(:authenticated_resource) { nil } 383 | let(:owned_by_authenticated_resource) { true } 384 | 385 | it { expect(perform).to eq(template) } 386 | end 387 | 388 | context "with parent_resource option" do 389 | let(:parent_resource_name) { "portfolio" } 390 | let(:template) do 391 | <<~CONTROLLER 392 | class Api::Exposed::V1::BlogsController < Api::Exposed::V1::BaseController 393 | def index 394 | respond_with blogs 395 | end 396 | def show 397 | respond_with blog 398 | end 399 | def create 400 | respond_with blogs.create!(blog_params) 401 | end 402 | def update 403 | blog.update!(blog_params) 404 | respond_with blog 405 | end 406 | def destroy 407 | respond_with blog.destroy! 408 | end 409 | private 410 | def blog 411 | @blog ||= Blog.find_by!(id: params[:id]) 412 | end 413 | def blogs 414 | @blogs ||= portfolio.blogs 415 | end 416 | def portfolio 417 | @portfolio ||= Portfolio.find_by!(id: params[:portfolio_id]) 418 | end 419 | def blog_params 420 | params.require(:blog).permit( 421 | :title, 422 | :body, 423 | :portfolio_id 424 | ) 425 | end 426 | end 427 | CONTROLLER 428 | end 429 | 430 | it { expect(perform).to eq(template) } 431 | end 432 | 433 | context "with parent_resource owned by authenticated_resource" do 434 | let(:parent_resource_name) { "portfolio" } 435 | let(:authenticated_resource) { "user" } 436 | let(:owned_by_authenticated_resource) { true } 437 | let(:template) do 438 | <<~CONTROLLER 439 | class Api::Exposed::V1::BlogsController < Api::Exposed::V1::BaseController 440 | acts_as_token_authentication_handler_for User, fallback: :exception 441 | 442 | def index 443 | respond_with blogs 444 | end 445 | def show 446 | respond_with blog 447 | end 448 | def create 449 | respond_with blogs.create!(blog_params) 450 | end 451 | def update 452 | blog.update!(blog_params) 453 | respond_with blog 454 | end 455 | def destroy 456 | respond_with blog.destroy! 457 | end 458 | private 459 | def blog 460 | @blog ||= Blog.find_by!(id: params[:id]) 461 | end 462 | def blogs 463 | @blogs ||= portfolio.blogs 464 | end 465 | def portfolio 466 | @portfolio ||= Portfolio.find_by!(id: params[:portfolio_id]) 467 | end 468 | def blog_params 469 | params.require(:blog).permit( 470 | :title, 471 | :body, 472 | :portfolio_id 473 | ) 474 | end 475 | end 476 | CONTROLLER 477 | end 478 | 479 | it { expect(perform).to eq(template) } 480 | end 481 | end 482 | 483 | describe "#version_base_controller_tpl" do 484 | let(:expected_tpl) do 485 | <<~CONTROLLER 486 | class Api::Exposed::V1::BaseController < Api::Exposed::BaseController 487 | before_action do 488 | self.namespace_for_serializer = ::Api::Exposed::V1 489 | end 490 | end 491 | CONTROLLER 492 | end 493 | 494 | def perform 495 | generators_helper.version_base_controller_tpl 496 | end 497 | 498 | it { expect(perform).to eq(expected_tpl) } 499 | 500 | context "with another version" do 501 | let(:version_number) { "2" } 502 | 503 | let(:expected_tpl) do 504 | <<~CONTROLLER 505 | class Api::Exposed::V2::BaseController < Api::Exposed::BaseController 506 | before_action do 507 | self.namespace_for_serializer = ::Api::Exposed::V2 508 | end 509 | end 510 | CONTROLLER 511 | end 512 | 513 | it { expect(perform).to eq(expected_tpl) } 514 | end 515 | end 516 | end 517 | -------------------------------------------------------------------------------- /spec/dummy/spec/lib/power_api/generator_helper/pagination_helper_spec.rb: -------------------------------------------------------------------------------- 1 | RSpec.describe PowerApi::GeneratorHelper::PaginationHelper, type: :generator do 2 | describe "#api_pagination_initializer_path" do 3 | let(:expected_path) { "config/initializers/api_pagination.rb" } 4 | 5 | def perform 6 | generators_helper.api_pagination_initializer_path 7 | end 8 | 9 | it { expect(perform).to eq(expected_path) } 10 | end 11 | 12 | describe "api_pagination_initializer_tpl" do 13 | let(:template) do 14 | <<~API_PAGINATION 15 | ApiPagination.configure do |config| 16 | # If you have more than one gem included, you can choose a paginator. 17 | config.paginator = :kaminari 18 | 19 | # By default, this is set to 'Total' 20 | config.total_header = 'X-Total' 21 | 22 | # By default, this is set to 'Per-Page' 23 | config.per_page_header = 'X-Per-Page' 24 | 25 | # Optional: set this to add a header with the current page number. 26 | config.page_header = 'X-Page' 27 | 28 | # Optional: set this to add other response format. Useful with tools that define :jsonapi format 29 | # config.response_formats = [:json, :xml, :jsonapi] 30 | config.response_formats = [:jsonapi] 31 | 32 | # Optional: what parameter should be used to set the page option 33 | config.page_param do |params| 34 | params[:page][:number] if params[:page].is_a?(ActionController::Parameters) 35 | end 36 | 37 | # Optional: what parameter should be used to set the per page option 38 | config.per_page_param do |params| 39 | params[:page][:size] if params[:page].is_a?(ActionController::Parameters) 40 | end 41 | 42 | # Optional: Include the total and last_page link header 43 | # By default, this is set to true 44 | # Note: When using kaminari, this prevents the count call to the database 45 | config.include_total = true 46 | end 47 | API_PAGINATION 48 | end 49 | 50 | def perform 51 | generators_helper.api_pagination_initializer_tpl 52 | end 53 | 54 | it { expect(perform).to eq(template) } 55 | end 56 | end 57 | -------------------------------------------------------------------------------- /spec/dummy/spec/lib/power_api/generator_helper/resource_helper_spec.rb: -------------------------------------------------------------------------------- 1 | RSpec.describe PowerApi::GeneratorHelper::ResourceHelper, type: :generator do 2 | describe "#resource" do 3 | let(:resource) { generators_helper.resource } 4 | 5 | it_behaves_like('ActiveRecord resource') 6 | it_behaves_like('ActiveRecord resource attributes', :resource_attributes) 7 | end 8 | 9 | describe "#parent_resource" do 10 | let(:parent_resource_name) { "blog" } 11 | let(:resource) { generators_helper.parent_resource } 12 | 13 | it_behaves_like('ActiveRecord resource') 14 | end 15 | 16 | describe "#parent_resource?" do 17 | let(:parent_resource_name) { "blog" } 18 | 19 | def perform 20 | generators_helper.parent_resource? 21 | end 22 | 23 | it { expect(perform).to eq(true) } 24 | 25 | context "with no parent resource name" do 26 | let(:parent_resource_name) { nil } 27 | 28 | it { expect(perform).to eq(false) } 29 | end 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /spec/dummy/spec/lib/power_api/generator_helper/routes_helper_spec.rb: -------------------------------------------------------------------------------- 1 | RSpec.describe PowerApi::GeneratorHelper::RoutesHelper, type: :generator do 2 | describe "#routes_path" do 3 | let(:expected_path) { "config/routes.rb" } 4 | 5 | def perform 6 | generators_helper.routes_path 7 | end 8 | 9 | it { expect(perform).to eq(expected_path) } 10 | end 11 | 12 | describe "#api_current_route_namespace_line_regex" do 13 | let(:expected_regex) { /Api::Exposed::V1[^\n]*/ } 14 | 15 | def perform 16 | generators_helper.api_current_route_namespace_line_regex 17 | end 18 | 19 | it { expect(perform).to eq(expected_regex) } 20 | 21 | context "without version" do 22 | let(:version_number) { "" } 23 | let(:expected_regex) { /namespace :internal[^\n]*/ } 24 | 25 | it { expect(perform).to eq(expected_regex) } 26 | end 27 | end 28 | 29 | describe "#parent_resource_routes_line_regex" do 30 | def perform 31 | generators_helper.parent_resource_routes_line_regex 32 | end 33 | 34 | it { expect { perform }.to raise_error("missing parent_resource") } 35 | 36 | context "with parent_resource" do 37 | let(:expected_regex) { /resources :users[^\n]*/ } 38 | let(:parent_resource_name) { "user" } 39 | 40 | it { expect(perform).to eq(expected_regex) } 41 | end 42 | end 43 | 44 | describe "#resource_route_tpl" do 45 | let(:actions) { [] } 46 | let(:expected_tpl) { "resources :blogs" } 47 | let(:parent_resource_name) { "user" } 48 | let(:is_parent) { false } 49 | 50 | def perform 51 | generators_helper.resource_route_tpl(actions: actions, is_parent: is_parent) 52 | end 53 | 54 | it { expect(perform).to eq(expected_tpl) } 55 | 56 | context "with specific actions" do 57 | let(:actions) { ["index", "create"] } 58 | let(:expected_tpl) { "resources :blogs, only: [:index, :create]" } 59 | 60 | it { expect(perform).to eq(expected_tpl) } 61 | end 62 | 63 | context "with is_parent option actions" do 64 | let(:is_parent) { true } 65 | let(:expected_tpl) { "resources :users" } 66 | 67 | it { expect(perform).to eq(expected_tpl) } 68 | end 69 | end 70 | 71 | describe "routes_line_to_inject_new_version" do 72 | let(:expected_line) do 73 | "routes.draw do\n" 74 | end 75 | 76 | def perform 77 | generators_helper.routes_line_to_inject_new_version 78 | end 79 | 80 | it { expect(perform).to eq(expected_line) } 81 | 82 | context "when is not the first version" do 83 | let(:version_number) { "2" } 84 | 85 | let(:expected_line) do 86 | "'/api' do\n" 87 | end 88 | 89 | it { expect(perform).to eq(expected_line) } 90 | end 91 | end 92 | 93 | describe "#version_route_tpl" do 94 | let(:expected_tpl) do 95 | <<~ROUTE 96 | scope path: '/api' do 97 | api_version(module: 'Api::Exposed::V1', path: { value: 'v1' }, defaults: { format: 'json' }) do 98 | end 99 | end 100 | ROUTE 101 | end 102 | 103 | def perform 104 | generators_helper.version_route_tpl 105 | end 106 | 107 | it { expect(perform).to eq(expected_tpl) } 108 | 109 | context "when is not the first version" do 110 | let(:version_number) { "2" } 111 | 112 | let(:expected_tpl) do 113 | <<~ROUTE 114 | api_version(module: 'Api::Exposed::V2', path: { value: 'v2' }, defaults: { format: 'json' }) do 115 | end 116 | ROUTE 117 | end 118 | 119 | it { expect(perform).to eq(expected_tpl.delete_suffix("\n")) } 120 | end 121 | end 122 | 123 | describe "#internal_route_tpl" do 124 | let(:expected_tpl) do 125 | <<~ROUTE 126 | namespace :api, defaults: { format: :json } do 127 | namespace :internal do 128 | end 129 | end 130 | ROUTE 131 | end 132 | 133 | def perform 134 | generators_helper.internal_route_tpl 135 | end 136 | 137 | it { expect(perform).to eq(expected_tpl) } 138 | end 139 | 140 | describe "#parent_route_exist?" do 141 | let(:parent_resource_name) { "user" } 142 | let(:line) { nil } 143 | 144 | def perform 145 | generators_helper.parent_route_exist? 146 | end 147 | 148 | before { mock_file_content("config/routes.rb", [line]) } 149 | 150 | context "with file line not matching regex" do 151 | let(:line) { "X" } 152 | 153 | it { expect(perform).to eq(false) } 154 | end 155 | 156 | context "with no parent_resource" do 157 | let(:parent_resource_name) { nil } 158 | 159 | it { expect { perform }.to raise_error("missing parent_resource") } 160 | end 161 | 162 | context "with file line matching regex" do 163 | let(:line) { "resources :users" } 164 | 165 | it { expect(perform).to eq(true) } 166 | end 167 | end 168 | 169 | describe "#parent_route_already_have_children?" do 170 | let(:parent_resource_name) { "user" } 171 | let(:line) { nil } 172 | 173 | def perform 174 | generators_helper.parent_route_already_have_children? 175 | end 176 | 177 | before { mock_file_content("config/routes.rb", [line]) } 178 | 179 | context "with file line not matching regex" do 180 | let(:line) { "X" } 181 | 182 | it { expect(perform).to eq(false) } 183 | end 184 | 185 | context "with no parent_resource" do 186 | let(:parent_resource_name) { nil } 187 | 188 | it { expect { perform }.to raise_error("missing parent_resource") } 189 | end 190 | 191 | context "with parent line found but with no children" do 192 | let(:line) { "resources :users" } 193 | 194 | it { expect(perform).to eq(false) } 195 | end 196 | 197 | context "with parent line found with children" do 198 | let(:line) { "resources :users do" } 199 | 200 | it { expect(perform).to eq(true) } 201 | end 202 | end 203 | end 204 | -------------------------------------------------------------------------------- /spec/dummy/spec/lib/power_api/generator_helper/rspec_controller_helper_spec.rb: -------------------------------------------------------------------------------- 1 | describe PowerApi::GeneratorHelper::RspecControllerHelper, type: :generator do 2 | describe "#resource_spec_path" do 3 | let(:expected_path) { "spec/requests/api/exposed/v1/blogs_spec.rb" } 4 | 5 | def perform 6 | generators_helper.resource_spec_path 7 | end 8 | 9 | it { expect(perform).to eq(expected_path) } 10 | 11 | context "when nil version" do 12 | let(:version_number) { nil } 13 | let(:expected_path) { "spec/requests/api/internal/blogs_spec.rb" } 14 | 15 | it { expect(perform).to eq(expected_path) } 16 | end 17 | end 18 | 19 | describe "#resource_spec_tpl" do 20 | let(:template) do 21 | <<~SPEC 22 | require 'rails_helper' 23 | 24 | RSpec.describe 'Api::Exposed::V1::BlogsControllers', type: :request do 25 | describe 'GET /index' do 26 | let!(:blogs) { create_list(:blog, 5) } 27 | let(:collection) { JSON.parse(response.body)['blogs'] } 28 | let(:params) { {} } 29 | 30 | def perform 31 | get '/api/v1/blogs', params: params 32 | end 33 | 34 | before do 35 | perform 36 | end 37 | 38 | it { expect(collection.count).to eq(5) } 39 | it { expect(response.status).to eq(200) } 40 | end 41 | 42 | describe 'POST /create' do 43 | let(:params) do 44 | { 45 | blog: { 46 | title: 'Some title', 47 | body: 'Some body' 48 | } 49 | } 50 | end 51 | 52 | let(:attributes) do 53 | JSON.parse(response.body)['blog'].symbolize_keys 54 | end 55 | def perform 56 | post '/api/v1/blogs', params: params 57 | end 58 | 59 | before do 60 | perform 61 | end 62 | 63 | it { expect(attributes).to include(params[:blog]) } 64 | it { expect(response.status).to eq(201) } 65 | 66 | context 'with invalid attributes' do 67 | let(:params) do 68 | { 69 | blog: { 70 | title: nil} 71 | } 72 | end 73 | 74 | it { expect(response.status).to eq(400) } 75 | end 76 | 77 | end 78 | 79 | describe 'GET /show' do 80 | let(:blog) { create(:blog) } 81 | let(:blog_id) { blog.id.to_s } 82 | 83 | let(:attributes) do 84 | JSON.parse(response.body)['blog'].symbolize_keys 85 | end 86 | def perform 87 | get '/api/v1/blogs/' + blog_id 88 | end 89 | 90 | before do 91 | perform 92 | end 93 | 94 | it { expect(response.status).to eq(200) } 95 | 96 | context 'with resource not found' do 97 | let(:blog_id) { '666' } 98 | it { expect(response.status).to eq(404) } 99 | end 100 | end 101 | 102 | describe 'PUT /update' do 103 | let(:blog) { create(:blog) } 104 | let(:blog_id) { blog.id.to_s } 105 | 106 | let(:params) do 107 | { 108 | blog: { 109 | title: 'Some title', 110 | body: 'Some body' 111 | } 112 | } 113 | end 114 | 115 | let(:attributes) do 116 | JSON.parse(response.body)['blog'].symbolize_keys 117 | end 118 | def perform 119 | put '/api/v1/blogs/' + blog_id, params: params 120 | end 121 | 122 | before do 123 | perform 124 | end 125 | 126 | it { expect(attributes).to include(params[:blog]) } 127 | it { expect(response.status).to eq(200) } 128 | 129 | context 'with invalid attributes' do 130 | let(:params) do 131 | { 132 | blog: { 133 | title: nil} 134 | } 135 | end 136 | 137 | it { expect(response.status).to eq(400) } 138 | end 139 | 140 | context 'with resource not found' do 141 | let(:blog_id) { '666' } 142 | it { expect(response.status).to eq(404) } 143 | end 144 | end 145 | 146 | describe 'DELETE /destroy' do 147 | let(:blog) { create(:blog) } 148 | let(:blog_id) { blog.id.to_s } 149 | 150 | def perform 151 | delete '/api/v1/blogs/' + blog_id 152 | end 153 | 154 | before do 155 | perform 156 | end 157 | 158 | it { expect(response.status).to eq(204) } 159 | 160 | context 'with resource not found' do 161 | let(:blog_id) { '666' } 162 | it { expect(response.status).to eq(404) } 163 | end 164 | end 165 | 166 | end 167 | SPEC 168 | end 169 | 170 | def perform 171 | generators_helper.resource_spec_tpl 172 | end 173 | 174 | it { expect(perform).to eq(template) } 175 | 176 | context "when nil version" do 177 | let(:version_number) { nil } 178 | 179 | it { expect(perform).to include("RSpec.describe 'Api::Internal::BlogsControllers'") } 180 | it { expect(perform).to include("get '/api/internal/blogs', params: params") } 181 | end 182 | 183 | context "with authenticated_resource option" do 184 | let(:authenticated_resource) { "user" } 185 | 186 | let(:template) do 187 | <<~SPEC 188 | require 'rails_helper' 189 | 190 | RSpec.describe 'Api::Exposed::V1::BlogsControllers', type: :request do 191 | let(:user) { create(:user) } 192 | describe 'GET /index' do 193 | let!(:blogs) { create_list(:blog, 5) } 194 | let(:collection) { JSON.parse(response.body)['blogs'] } 195 | let(:params) { {} } 196 | 197 | def perform 198 | get '/api/v1/blogs', params: params 199 | end 200 | 201 | context 'with authorized user' do 202 | before do 203 | sign_in(user) 204 | perform 205 | end 206 | 207 | it { expect(collection.count).to eq(5) } 208 | it { expect(response.status).to eq(200) } 209 | end 210 | 211 | context 'with unauthenticated user' do 212 | before { perform } 213 | 214 | it { expect(response.status).to eq(401) } 215 | end 216 | 217 | end 218 | 219 | describe 'POST /create' do 220 | let(:params) do 221 | { 222 | blog: { 223 | title: 'Some title', 224 | body: 'Some body' 225 | } 226 | } 227 | end 228 | 229 | let(:attributes) do 230 | JSON.parse(response.body)['blog'].symbolize_keys 231 | end 232 | def perform 233 | post '/api/v1/blogs', params: params 234 | end 235 | 236 | context 'with authorized user' do 237 | before do 238 | sign_in(user) 239 | perform 240 | end 241 | 242 | it { expect(attributes).to include(params[:blog]) } 243 | it { expect(response.status).to eq(201) } 244 | 245 | context 'with invalid attributes' do 246 | let(:params) do 247 | { 248 | blog: { 249 | title: nil} 250 | } 251 | end 252 | 253 | it { expect(response.status).to eq(400) } 254 | end 255 | 256 | end 257 | 258 | context 'with unauthenticated user' do 259 | before { perform } 260 | 261 | it { expect(response.status).to eq(401) } 262 | end 263 | 264 | end 265 | 266 | describe 'GET /show' do 267 | let(:blog) { create(:blog) } 268 | let(:blog_id) { blog.id.to_s } 269 | 270 | let(:attributes) do 271 | JSON.parse(response.body)['blog'].symbolize_keys 272 | end 273 | def perform 274 | get '/api/v1/blogs/' + blog_id 275 | end 276 | 277 | context 'with authorized user' do 278 | before do 279 | sign_in(user) 280 | perform 281 | end 282 | 283 | it { expect(response.status).to eq(200) } 284 | 285 | context 'with resource not found' do 286 | let(:blog_id) { '666' } 287 | it { expect(response.status).to eq(404) } 288 | end 289 | end 290 | 291 | context 'with unauthenticated user' do 292 | before { perform } 293 | 294 | it { expect(response.status).to eq(401) } 295 | end 296 | 297 | end 298 | 299 | describe 'PUT /update' do 300 | let(:blog) { create(:blog) } 301 | let(:blog_id) { blog.id.to_s } 302 | 303 | let(:params) do 304 | { 305 | blog: { 306 | title: 'Some title', 307 | body: 'Some body' 308 | } 309 | } 310 | end 311 | 312 | let(:attributes) do 313 | JSON.parse(response.body)['blog'].symbolize_keys 314 | end 315 | def perform 316 | put '/api/v1/blogs/' + blog_id, params: params 317 | end 318 | 319 | context 'with authorized user' do 320 | before do 321 | sign_in(user) 322 | perform 323 | end 324 | 325 | it { expect(attributes).to include(params[:blog]) } 326 | it { expect(response.status).to eq(200) } 327 | 328 | context 'with invalid attributes' do 329 | let(:params) do 330 | { 331 | blog: { 332 | title: nil} 333 | } 334 | end 335 | 336 | it { expect(response.status).to eq(400) } 337 | end 338 | 339 | context 'with resource not found' do 340 | let(:blog_id) { '666' } 341 | it { expect(response.status).to eq(404) } 342 | end 343 | end 344 | 345 | context 'with unauthenticated user' do 346 | before { perform } 347 | 348 | it { expect(response.status).to eq(401) } 349 | end 350 | 351 | end 352 | 353 | describe 'DELETE /destroy' do 354 | let(:blog) { create(:blog) } 355 | let(:blog_id) { blog.id.to_s } 356 | 357 | def perform 358 | delete '/api/v1/blogs/' + blog_id 359 | end 360 | 361 | context 'with authorized user' do 362 | before do 363 | sign_in(user) 364 | perform 365 | end 366 | 367 | it { expect(response.status).to eq(204) } 368 | 369 | context 'with resource not found' do 370 | let(:blog_id) { '666' } 371 | it { expect(response.status).to eq(404) } 372 | end 373 | end 374 | 375 | context 'with unauthenticated user' do 376 | before { perform } 377 | 378 | it { expect(response.status).to eq(401) } 379 | end 380 | 381 | end 382 | 383 | end 384 | SPEC 385 | end 386 | 387 | it { expect(perform).to eq(template) } 388 | 389 | context "with owned_by_authenticated_resource option" do 390 | let(:authenticated_resource) { "user" } 391 | let(:owned_by_authenticated_resource) { true } 392 | 393 | it { expect(perform).to include("create_list(:blog, 5, user: user)") } 394 | end 395 | end 396 | 397 | context "with parent_resource option" do 398 | let(:parent_resource_name) { "portfolio" } 399 | 400 | let(:template) do 401 | <<~SPEC 402 | require 'rails_helper' 403 | 404 | RSpec.describe 'Api::Exposed::V1::BlogsControllers', type: :request do 405 | let(:portfolio) { create(:portfolio) } 406 | let(:portfolio_id) { portfolio.id } 407 | 408 | describe 'GET /index' do 409 | let!(:blogs) { create_list(:blog, 5, portfolio: portfolio) } 410 | let(:collection) { JSON.parse(response.body)['blogs'] } 411 | let(:params) { {} } 412 | 413 | def perform 414 | get '/api/v1/portfolios/' + portfolio.id.to_s + '/blogs', params: params 415 | end 416 | 417 | before do 418 | perform 419 | end 420 | 421 | it { expect(collection.count).to eq(5) } 422 | it { expect(response.status).to eq(200) } 423 | end 424 | 425 | describe 'POST /create' do 426 | let(:params) do 427 | { 428 | blog: { 429 | title: 'Some title', 430 | body: 'Some body' 431 | } 432 | } 433 | end 434 | 435 | let(:attributes) do 436 | JSON.parse(response.body)['blog'].symbolize_keys 437 | end 438 | def perform 439 | post '/api/v1/portfolios/' + portfolio.id.to_s + '/blogs', params: params 440 | end 441 | 442 | before do 443 | perform 444 | end 445 | 446 | it { expect(attributes).to include(params[:blog]) } 447 | it { expect(response.status).to eq(201) } 448 | 449 | context 'with invalid attributes' do 450 | let(:params) do 451 | { 452 | blog: { 453 | title: nil} 454 | } 455 | end 456 | 457 | it { expect(response.status).to eq(400) } 458 | end 459 | 460 | end 461 | 462 | describe 'GET /show' do 463 | let(:blog) { create(:blog, portfolio: portfolio) } 464 | let(:blog_id) { blog.id.to_s } 465 | 466 | let(:attributes) do 467 | JSON.parse(response.body)['blog'].symbolize_keys 468 | end 469 | def perform 470 | get '/api/v1/blogs/' + blog_id 471 | end 472 | 473 | before do 474 | perform 475 | end 476 | 477 | it { expect(response.status).to eq(200) } 478 | 479 | context 'with resource not found' do 480 | let(:blog_id) { '666' } 481 | it { expect(response.status).to eq(404) } 482 | end 483 | end 484 | 485 | describe 'PUT /update' do 486 | let(:blog) { create(:blog, portfolio: portfolio) } 487 | let(:blog_id) { blog.id.to_s } 488 | 489 | let(:params) do 490 | { 491 | blog: { 492 | title: 'Some title', 493 | body: 'Some body' 494 | } 495 | } 496 | end 497 | 498 | let(:attributes) do 499 | JSON.parse(response.body)['blog'].symbolize_keys 500 | end 501 | def perform 502 | put '/api/v1/blogs/' + blog_id, params: params 503 | end 504 | 505 | before do 506 | perform 507 | end 508 | 509 | it { expect(attributes).to include(params[:blog]) } 510 | it { expect(response.status).to eq(200) } 511 | 512 | context 'with invalid attributes' do 513 | let(:params) do 514 | { 515 | blog: { 516 | title: nil} 517 | } 518 | end 519 | 520 | it { expect(response.status).to eq(400) } 521 | end 522 | 523 | context 'with resource not found' do 524 | let(:blog_id) { '666' } 525 | it { expect(response.status).to eq(404) } 526 | end 527 | end 528 | 529 | describe 'DELETE /destroy' do 530 | let(:blog) { create(:blog, portfolio: portfolio) } 531 | let(:blog_id) { blog.id.to_s } 532 | 533 | def perform 534 | delete '/api/v1/blogs/' + blog_id 535 | end 536 | 537 | before do 538 | perform 539 | end 540 | 541 | it { expect(response.status).to eq(204) } 542 | 543 | context 'with resource not found' do 544 | let(:blog_id) { '666' } 545 | it { expect(response.status).to eq(404) } 546 | end 547 | end 548 | 549 | end 550 | SPEC 551 | end 552 | 553 | it { expect(perform).to eq(template) } 554 | end 555 | 556 | context 'with only some actions (show and create)' do 557 | let(:controller_actions) do 558 | [ 559 | "show", 560 | "create" 561 | ] 562 | end 563 | 564 | it { expect(perform).to include("describe 'GET /show'") } 565 | it { expect(perform).to include("describe 'POST /create'") } 566 | it { expect(perform).not_to include("describe 'DELETE /destroy'") } 567 | it { expect(perform).not_to include("describe 'PUT /update'") } 568 | it { expect(perform).not_to include("describe 'GET /index'") } 569 | end 570 | end 571 | end 572 | -------------------------------------------------------------------------------- /spec/dummy/spec/lib/power_api/generator_helper/simple_token_auth_helper_spec.rb: -------------------------------------------------------------------------------- 1 | RSpec.describe PowerApi::GeneratorHelper::SimpleTokenAuthHelper, type: :generator do 2 | describe "#authenticated_resource" do 3 | let(:authenticated_resource) { "blog" } 4 | let(:resource) { generators_helper.authenticated_resource } 5 | 6 | it_behaves_like('ActiveRecord resource') do 7 | describe "#authenticated_resources_migrations" do 8 | let(:expected) do 9 | "migration add_authentication_token_to_blogs authentication_token:string{30}:uniq" 10 | end 11 | 12 | it { expect(resource.authenticated_resource_migration).to eq(expected) } 13 | end 14 | 15 | describe "current_authenticated_resource" do 16 | it { expect(generators_helper.current_authenticated_resource).to eq("current_blog") } 17 | end 18 | end 19 | end 20 | 21 | describe "#authenticated_resources=" do 22 | let(:resources_names) { ["blog"] } 23 | let(:resource) { resources.first } 24 | 25 | def resources 26 | generators_helper.authenticated_resources = resources_names 27 | generators_helper.authenticated_resources 28 | end 29 | 30 | it { expect(resources.count).to eq(1) } 31 | it { expect(resources.first).to be_a(described_class::SimpleTokenAuthResource) } 32 | 33 | it_behaves_like('ActiveRecord resource') do 34 | describe "#authenticated_resources_migrations" do 35 | let(:expected) do 36 | "migration add_authentication_token_to_blogs authentication_token:string{30}:uniq" 37 | end 38 | 39 | it { expect(resource.authenticated_resource_migration).to eq(expected) } 40 | end 41 | end 42 | end 43 | 44 | describe "#owned_by_authenticated_resource?" do 45 | let(:authenticated_resource) { "user" } 46 | let(:owned_by_authenticated_resource) { true } 47 | let(:parent_resource_name) { nil } 48 | 49 | def perform 50 | generators_helper.owned_by_authenticated_resource? 51 | end 52 | 53 | it { expect(perform).to eq(true) } 54 | 55 | context "with no authenticated_resource" do 56 | let(:authenticated_resource) { nil } 57 | 58 | it { expect(perform).to eq(false) } 59 | end 60 | 61 | context "with no owned_by_authenticated_resource" do 62 | let(:owned_by_authenticated_resource) { false } 63 | 64 | it { expect(perform).to eq(false) } 65 | end 66 | 67 | context "with no parent_resource_name" do 68 | let(:parent_resource_name) { "portfolio" } 69 | 70 | it { expect(perform).to eq(false) } 71 | end 72 | end 73 | 74 | describe "#simple_token_auth_method" do 75 | let(:expected) do 76 | " acts_as_token_authenticatable\n\n" 77 | end 78 | 79 | it { expect(generators_helper.simple_token_auth_method).to eq(expected) } 80 | end 81 | 82 | describe "#simple_token_auth_initializer_path" do 83 | let(:expected_path) { "spec/swagger/.gitkeep" } 84 | 85 | def perform 86 | generators_helper.simple_token_auth_initializer_path 87 | end 88 | 89 | it { expect(perform).to eq("config/initializers/simple_token_authentication.rb") } 90 | end 91 | 92 | describe "#simple_token_auth_initializer_tpl" do 93 | let(:expected) do 94 | <<~INITIALIZER 95 | SimpleTokenAuthentication.configure do |config| 96 | # Configure the session persistence policy after a successful sign in, 97 | # in other words, if the authentication token acts as a signin token. 98 | # If true, user is stored in the session and the authentication token and 99 | # email may be provided only once. 100 | # If false, users must provide their authentication token and email at every request. 101 | # config.sign_in_token = false 102 | 103 | # Configure the name of the HTTP headers watched for authentication. 104 | # 105 | # Default header names for a given token authenticatable entity follow the pattern: 106 | # { entity: { authentication_token: 'X-Entity-Token', email: 'X-Entity-Email'} } 107 | # 108 | # When several token authenticatable models are defined, custom header names 109 | # can be specified for none, any, or all of them. 110 | # 111 | # Note: when using the identifiers options, this option behaviour is modified. 112 | # Please see the example below. 113 | # 114 | # Examples 115 | # 116 | # Given User and SuperAdmin are token authenticatable, 117 | # When the following configuration is used: 118 | # `config.header_names = { super_admin: { authentication_token: 'X-Admin-Auth-Token' } }` 119 | # Then the token authentification handler for User watches the following headers: 120 | # `X-User-Token, X-User-Email` 121 | # And the token authentification handler for SuperAdmin watches the following headers: 122 | # `X-Admin-Auth-Token, X-SuperAdmin-Email` 123 | # 124 | # When the identifiers option is set: 125 | # `config.identifiers = { super_admin: :phone_number }` 126 | # Then both the header names identifier key and default value are modified accordingly: 127 | # `config.header_names = { super_admin: { phone_number: 'X-SuperAdmin-PhoneNumber' } }` 128 | # 129 | # config.header_names = { user: { authentication_token: 'X-User-Token', email: 'X-User-Email' } } 130 | 131 | # Configure the name of the attribute used to identify the user for authentication. 132 | # That attribute must exist in your model. 133 | # 134 | # The default identifiers follow the pattern: 135 | # { entity: 'email' } 136 | # 137 | # Note: the identifer must match your Devise configuration, 138 | # see https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-using-their-username-or-email-address#tell-devise-to-use-username-in-the-authentication_keys 139 | # 140 | # Note: setting this option does modify the header_names behaviour, 141 | # see the header_names section above. 142 | # 143 | # Example: 144 | # 145 | # `config.identifiers = { super_admin: 'phone_number', user: 'uuid' }` 146 | # 147 | # config.identifiers = { user: 'email' } 148 | 149 | # Configure the Devise trackable strategy integration. 150 | # 151 | # If true, tracking is disabled for token authentication: signing in through 152 | # token authentication won't modify the Devise trackable statistics. 153 | # 154 | # If false, given Devise trackable is configured for the relevant model, 155 | # then signing in through token authentication will be tracked as any other sign in. 156 | # 157 | # config.skip_devise_trackable = true 158 | end 159 | INITIALIZER 160 | end 161 | 162 | it { expect(generators_helper.simple_token_auth_initializer_tpl).to eq(expected) } 163 | end 164 | end 165 | -------------------------------------------------------------------------------- /spec/dummy/spec/support/shared_examples/active_record_resource.rb: -------------------------------------------------------------------------------- 1 | shared_examples 'ActiveRecord resource' do 2 | describe "#id" do 3 | def perform 4 | resource.id 5 | end 6 | 7 | it { expect(perform).to eq("blog_id") } 8 | end 9 | 10 | describe "#upcase" do 11 | def perform 12 | resource.upcase 13 | end 14 | 15 | it { expect(perform).to eq("BLOG") } 16 | end 17 | 18 | describe "#upcase_plural" do 19 | def perform 20 | resource.upcase_plural 21 | end 22 | 23 | it { expect(perform).to eq("BLOGS") } 24 | end 25 | 26 | describe "#camel" do 27 | def perform 28 | resource.camel 29 | end 30 | 31 | it { expect(perform).to eq("Blog") } 32 | end 33 | 34 | describe "#plural" do 35 | def perform 36 | resource.plural 37 | end 38 | 39 | it { expect(perform).to eq("blogs") } 40 | end 41 | 42 | describe "#snake_case" do 43 | def perform 44 | resource.snake_case 45 | end 46 | 47 | it { expect(perform).to eq("blog") } 48 | end 49 | 50 | describe "#titleized" do 51 | def perform 52 | resource.titleized 53 | end 54 | 55 | it { expect(perform).to eq("Blog") } 56 | end 57 | 58 | describe "#plural_titleized" do 59 | def perform 60 | resource.plural_titleized 61 | end 62 | 63 | it { expect(perform).to eq("Blogs") } 64 | end 65 | 66 | describe "#resource_name=" do 67 | context "with invalid resource name" do 68 | let(:resource_name) { "ticket" } 69 | 70 | it { expect { generators_helper }.to raise_error(/Invalid resource name/) } 71 | end 72 | 73 | context "with missing resource name" do 74 | let(:resource_name) { "" } 75 | 76 | it { expect { generators_helper }.to raise_error(/Invalid resource name/) } 77 | end 78 | 79 | context "when resource is not an active record model" do 80 | let(:resource_name) { "power_api" } 81 | 82 | it { expect { generators_helper }.to raise_error("resource is not an active record model") } 83 | end 84 | end 85 | 86 | describe "#class_definition_line" do 87 | def perform 88 | resource.class_definition_line 89 | end 90 | 91 | it { expect(perform).to eq("class Blog < ApplicationRecord\n") } 92 | end 93 | 94 | describe "#path" do 95 | def perform 96 | resource.path 97 | end 98 | 99 | it { expect(perform).to eq("app/models/blog.rb") } 100 | end 101 | end 102 | -------------------------------------------------------------------------------- /spec/dummy/spec/support/shared_examples/active_record_resource_atrributes.rb: -------------------------------------------------------------------------------- 1 | # rubocop:disable Metrics/LineLength 2 | shared_examples 'ActiveRecord resource attributes' do |attributes_key| 3 | describe "#resource_attributes" do 4 | let(:expected_attributes) do 5 | [ 6 | { name: :id, type: :integer, example: kind_of(Integer), required: false }, 7 | { name: :title, type: :string, example: "'Some title'", required: true }, 8 | { name: :body, type: :text, example: "'Some body'", required: true }, 9 | { name: :created_at, type: :datetime, example: "'1984-06-04 09:00'", required: false }, 10 | { name: :updated_at, type: :datetime, example: "'1984-06-04 09:00'", required: false }, 11 | { name: :portfolio_id, type: :integer, example: kind_of(Integer), required: false } 12 | ] 13 | end 14 | 15 | def perform 16 | resource.resource_attributes 17 | end 18 | 19 | it { expect(perform).to match(expected_attributes) } 20 | 21 | context "with selected attributes" do 22 | let(attributes_key) { %w{title body} } 23 | let(:expected_attributes) do 24 | [ 25 | { name: :id, type: :integer, example: kind_of(Integer), required: false }, 26 | { name: :title, type: :string, example: "'Some title'", required: true }, 27 | { name: :body, type: :text, example: "'Some body'", required: true } 28 | ] 29 | end 30 | 31 | it { expect(perform).to match(expected_attributes) } 32 | end 33 | 34 | context "with attributes not present in model" do 35 | let(attributes_key) { %w{title bloody} } 36 | let(:expected_attributes) do 37 | [ 38 | { name: :id, type: :integer, example: kind_of(Integer), required: false }, 39 | { name: :title, type: :string, example: "'Some title'", required: true } 40 | ] 41 | end 42 | 43 | it { expect(perform).to match(expected_attributes) } 44 | end 45 | end 46 | 47 | describe "#required_resource_attributes" do 48 | let(:include_id) { false } 49 | let(:expected_attributes) do 50 | [ 51 | { name: :title, type: :string, example: "'Some title'", required: true }, 52 | { name: :body, type: :text, example: "'Some body'", required: true } 53 | ] 54 | end 55 | 56 | def perform 57 | resource.required_resource_attributes(include_id: include_id) 58 | end 59 | 60 | it { expect(perform).to eq(expected_attributes) } 61 | 62 | context "with included id" do 63 | let(:include_id) { true } 64 | let(:expected_attributes) do 65 | [ 66 | { name: :id, type: :integer, example: kind_of(Integer), required: false }, 67 | { name: :title, type: :string, example: "'Some title'", required: true }, 68 | { name: :body, type: :text, example: "'Some body'", required: true } 69 | ] 70 | end 71 | 72 | it { expect(perform).to match(expected_attributes) } 73 | end 74 | end 75 | 76 | describe "#required_attributes_names" do 77 | let(:expected_attributes) do 78 | [ 79 | :title, 80 | :body 81 | ] 82 | end 83 | 84 | def perform 85 | resource.required_attributes_names 86 | end 87 | 88 | it { expect(perform).to eq(expected_attributes) } 89 | end 90 | 91 | describe "#optional_resource_attributes" do 92 | let(:expected_attributes) do 93 | [ 94 | { name: :portfolio_id, type: :integer, example: kind_of(Integer), required: false } 95 | ] 96 | end 97 | 98 | def perform 99 | resource.optional_resource_attributes 100 | end 101 | 102 | it { expect(perform).to match(expected_attributes) } 103 | end 104 | 105 | describe "#attributes_names" do 106 | let(:expected_attributes) do 107 | [ 108 | :id, 109 | :title, 110 | :body, 111 | :created_at, 112 | :updated_at, 113 | :portfolio_id 114 | ] 115 | end 116 | 117 | def perform 118 | resource.attributes_names 119 | end 120 | 121 | it { expect(perform).to eq(expected_attributes) } 122 | end 123 | 124 | describe "#permitted_attributes" do 125 | let(:expected_attributes) do 126 | [ 127 | { name: :title, type: :string, example: "'Some title'", required: true }, 128 | { name: :body, type: :text, example: "'Some body'", required: true }, 129 | { name: :portfolio_id, type: :integer, example: kind_of(Integer), required: false } 130 | ] 131 | end 132 | 133 | def perform 134 | resource.permitted_attributes 135 | end 136 | 137 | it { expect(perform).to match(expected_attributes) } 138 | end 139 | 140 | describe "#permitted_attributes_names" do 141 | let(:expected_attributes) do 142 | [ 143 | :title, 144 | :body, 145 | :portfolio_id 146 | ] 147 | end 148 | 149 | def perform 150 | resource.permitted_attributes_names 151 | end 152 | 153 | it { expect(perform).to eq(expected_attributes) } 154 | end 155 | 156 | describe "#attributes_symbols_text_list" do 157 | let(:expected_result) do 158 | <<~ATTRS 159 | :id, 160 | :title, 161 | :body, 162 | :created_at, 163 | :updated_at, 164 | :portfolio_id 165 | ATTRS 166 | end 167 | 168 | def perform 169 | resource.attributes_symbols_text_list 170 | end 171 | 172 | it { expect(perform).to eq(expected_result) } 173 | end 174 | 175 | describe "#resource_attributes=" do 176 | context "with provided attributes resulting in empty attributes config" do 177 | let(attributes_key) { %w{invalid attrs} } 178 | 179 | it { expect { generators_helper }.to raise_error("at least one attribute must be added") } 180 | end 181 | end 182 | end 183 | # rubocop:enable Metrics/LineLength 184 | -------------------------------------------------------------------------------- /spec/dummy/spec/support/test_generator_helpers.rb: -------------------------------------------------------------------------------- 1 | module TestGeneratorHelpers 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | subject(:generators_helper) { PowerApi::GeneratorHelpers.new(init_params) } 6 | 7 | let(:version_number) { "1" } 8 | let(:resource_name) { "blog" } 9 | let(:authenticated_resource) { nil } 10 | let(:parent_resource_name) { nil } 11 | let(:owned_by_authenticated_resource) { false } 12 | let(:resource_attributes) { nil } 13 | let(:controller_actions) { [] } 14 | let(:use_paginator) { false } 15 | let(:allow_filters) { false } 16 | 17 | let(:init_params) do 18 | { 19 | version_number: version_number, 20 | resource: resource_name, 21 | resource_attributes: resource_attributes, 22 | controller_actions: controller_actions, 23 | parent_resource: parent_resource_name, 24 | use_paginator: use_paginator, 25 | authenticated_resource: authenticated_resource, 26 | owned_by_authenticated_resource: owned_by_authenticated_resource, 27 | allow_filters: allow_filters 28 | } 29 | end 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /spec/dummy/spec/support/test_helpers.rb: -------------------------------------------------------------------------------- 1 | module TestHelpers 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | def mock_file_content(expected_path, content_lines) 6 | allow(File).to receive(:readlines).with( 7 | File.join(Rails.root, expected_path) 8 | ).and_return(content_lines) 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /spec/dummy/storage/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/platanus/power_api/fc84727c8772199266af4d66f88b2bdd6dd0c4f4/spec/dummy/storage/.keep -------------------------------------------------------------------------------- /spec/rails_helper.rb: -------------------------------------------------------------------------------- 1 | require 'simplecov' 2 | require 'coveralls' 3 | 4 | formatters = [SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter] 5 | SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter::new(formatters) 6 | 7 | SimpleCov.start do 8 | add_filter do |src| 9 | r = [ 10 | src.filename =~ /lib/, 11 | src.filename =~ /models/, 12 | src.filename =~ /controllers/ 13 | ].uniq 14 | r.count == 1 && r.first.nil? 15 | end 16 | 17 | add_filter "engine.rb" 18 | add_filter "spec.rb" 19 | end 20 | 21 | ENV["RAILS_ENV"] ||= "test" 22 | require File.expand_path("../../spec/dummy/config/environment", __FILE__) 23 | abort("The Rails environment is running in production mode!") if Rails.env.production? 24 | require "pry" 25 | require "spec_helper" 26 | require "rspec/rails" 27 | require "factory_bot_rails" 28 | 29 | ActiveRecord::Migration.maintain_test_schema! 30 | 31 | Dir[::Rails.root.join("spec/support/**/*.rb")].each { |f| require f } 32 | 33 | RSpec.configure do |config| 34 | config.fixture_path = "#{::Rails.root}/spec/assets" 35 | config.use_transactional_fixtures = true 36 | config.infer_spec_type_from_file_location! 37 | config.filter_rails_from_backtrace! 38 | 39 | config.filter_run :focus 40 | config.run_all_when_everything_filtered = true 41 | 42 | FactoryBot.definition_file_paths = ["#{::Rails.root}/spec/factories"] 43 | FactoryBot.find_definitions 44 | 45 | config.include FactoryBot::Syntax::Methods 46 | config.include ActionDispatch::TestProcess 47 | config.include TestHelpers 48 | config.include TestGeneratorHelpers, type: :generator 49 | end 50 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | RSpec.configure do |config| 2 | config.expect_with :rspec do |expectations| 3 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true 4 | end 5 | 6 | config.mock_with :rspec do |mocks| 7 | mocks.verify_partial_doubles = true 8 | end 9 | end 10 | --------------------------------------------------------------------------------