├── .github ├── FUNDING.yml └── workflows │ ├── lint.yml │ └── test.yml ├── .gitignore ├── .rubocop.yml ├── .ruby-version ├── CHANGELOG.md ├── Gemfile ├── Gemfile.lock ├── LICENSE ├── README.md ├── Rakefile ├── bin └── test ├── jsonapi-scopes.gemspec ├── lib └── jsonapi │ ├── exceptions.rb │ ├── scopes.rb │ └── scopes │ ├── filters.rb │ ├── includes.rb │ ├── sorts.rb │ └── version.rb └── test ├── dummy ├── .rspec ├── .ruby-version ├── Rakefile ├── app │ ├── assets │ │ ├── config │ │ │ └── manifest.js │ │ ├── images │ │ │ └── .keep │ │ └── stylesheets │ │ │ └── application.css │ ├── channels │ │ └── application_cable │ │ │ ├── channel.rb │ │ │ └── connection.rb │ ├── controllers │ │ ├── application_controller.rb │ │ └── concerns │ │ │ └── .keep │ ├── helpers │ │ └── application_helper.rb │ ├── javascript │ │ └── packs │ │ │ └── application.js │ ├── jobs │ │ └── application_job.rb │ ├── mailers │ │ └── application_mailer.rb │ ├── models │ │ ├── application_record.rb │ │ ├── concerns │ │ │ └── .keep │ │ ├── contact.rb │ │ ├── post.rb │ │ └── user.rb │ └── views │ │ └── layouts │ │ ├── application.html.erb │ │ ├── mailer.html.erb │ │ └── mailer.text.erb ├── bin │ ├── rails │ ├── rake │ ├── setup │ └── update ├── config.ru ├── config │ ├── application.rb │ ├── boot.rb │ ├── cable.yml │ ├── database.yml │ ├── environment.rb │ ├── environments │ │ ├── development.rb │ │ ├── production.rb │ │ └── test.rb │ ├── initializers │ │ ├── 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 │ │ └── wrap_parameters.rb │ ├── locales │ │ └── en.yml │ ├── puma.rb │ ├── routes.rb │ ├── spring.rb │ └── storage.yml ├── db │ ├── migrate │ │ ├── 20190511203334_create_contacts.rb │ │ └── 20190916201953_create_users.rb │ └── schema.rb ├── lib │ └── assets │ │ └── .keep ├── log │ └── .keep ├── public │ ├── 404.html │ ├── 422.html │ ├── 500.html │ ├── apple-touch-icon-precomposed.png │ ├── apple-touch-icon.png │ └── favicon.ico ├── spec │ ├── factories │ │ ├── contacts.rb │ │ ├── posts.rb │ │ └── users.rb │ ├── models │ │ ├── contact_spec.rb │ │ └── user_spec.rb │ ├── rails_helper.rb │ └── spec_helper.rb └── test │ ├── fixtures │ └── contacts.yml │ └── models │ └── contact_test.rb ├── jsonapi └── scopes_test.rb └── test_helper.rb /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: guillaumebriday 2 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Lint 2 | 3 | on: [push] 4 | 5 | jobs: 6 | rubocop: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v1 10 | - uses: actions/setup-ruby@v1 11 | with: 12 | ruby-version: 2.6.x 13 | - run: | 14 | sudo apt-get -yqq install libsqlite3-dev 15 | gem install bundler --no-document 16 | bundle install -j $(nproc) --quiet 17 | bundle exec rubocop 18 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: [push] 4 | 5 | jobs: 6 | rspec: 7 | runs-on: ubuntu-latest 8 | services: 9 | db: 10 | image: postgres:11-alpine 11 | ports: ['5432:5432'] 12 | env: 13 | POSTGRES_DB: test 14 | POSTGRES_PASSWORD: secret 15 | steps: 16 | - uses: actions/checkout@v1 17 | - uses: actions/setup-ruby@v1 18 | with: 19 | ruby-version: 2.6.x 20 | - env: 21 | DATABASE_URL: postgres://postgres:secret@localhost:5432/test 22 | RAILS_ENV: test 23 | run: | 24 | sudo apt-get -yqq install libpq-dev libsqlite3-dev 25 | gem install bundler --no-document 26 | bundle install -j $(nproc) --quiet 27 | cd test/dummy 28 | bundle exec rspec 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .bundle/ 2 | log/*.log 3 | pkg/ 4 | test/dummy/db/*.sqlite3 5 | test/dummy/db/*.sqlite3-journal 6 | test/dummy/log/*.log 7 | test/dummy/storage/ 8 | test/dummy/tmp/ 9 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | Metrics/LineLength: 2 | Enabled: false 3 | 4 | Documentation: 5 | Enabled: false 6 | 7 | Style/ClassAndModuleChildren: 8 | Enabled: false 9 | 10 | Metrics/AbcSize: 11 | Enabled: false 12 | 13 | Metrics/BlockLength: 14 | Enabled: false 15 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | 2.6.3 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | ## v0.4.1 - 2019-09-24 8 | ### Changed 9 | - Updating the Gemfile.lock 10 | - Updating readme 11 | 12 | ## v0.4.0 - 2019-09-24 13 | ### Added 14 | - Adding `Jsonapi::Include` module to handle dynamic includes like so: `/posts?include=comments,author` 15 | 16 | ## v0.3.0 - 2019-09-16 17 | ### Changed 18 | - Raise `Jsonapi::InvalidAttributeError` when attribute is invalid. 19 | 20 | ## v0.2.0 - 2019-08-01 21 | ### Fixed 22 | - Adding condition when spliting filter_params to prevent issue. 23 | 24 | ## v0.1.5 - 2019-07-20 25 | ### Changed 26 | - Using `Array.wrap` in apply_sort instead of `[].flatten`. 27 | - Adding specs on allowed sorted fields. 28 | 29 | ## v0.1.4 - 2019-07-17 30 | ### Added 31 | - `apply_filter` can now handle multiple matching with a comma separated list of values: `/contacts?filter[first_name]=Bruce,Peter` 32 | 33 | ## v0.1.3 - 2019-05-22 34 | ### Added 35 | - Add a changelog 36 | - Add specs 37 | - Add credits in README (https://github.com/guillaumebriday/jsonapi-scopes/commit/1f76b0ad822087a0305d102515946a756088d0c1) 38 | 39 | ### Changed 40 | - `apply_filter` use the method `all` to generate an ActiveRecord collection. 41 | - `apply_sort` has now optional params. 42 | 43 | ### Removed 44 | - Remove 'attr_reader` on `filters`. 45 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | source 'https://rubygems.org' 4 | git_source(:github) { |repo| "https://github.com/#{repo}.git" } 5 | 6 | # Declare your gem's dependencies in jsonapi-scopes.gemspec. 7 | # Bundler will treat runtime dependencies like base dependencies, and 8 | # development dependencies will be added by default to the :development group. 9 | gemspec 10 | 11 | # Declare any dependencies that are still in development here instead of in 12 | # your gemspec. These might include edge Rails or gems from your path or 13 | # Git. Remember to move these dependencies to your gemspec before releasing 14 | # your gem to rubygems.org. 15 | 16 | # To use a debugger 17 | # gem 'byebug', group: [:development, :test] 18 | 19 | gem 'database_cleaner' 20 | gem 'factory_bot' 21 | gem 'pg' 22 | gem 'rspec-rails' 23 | gem 'rubocop' 24 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | PATH 2 | remote: . 3 | specs: 4 | jsonapi-scopes (0.4.1) 5 | rails 6 | 7 | GEM 8 | remote: https://rubygems.org/ 9 | specs: 10 | actioncable (5.2.3) 11 | actionpack (= 5.2.3) 12 | nio4r (~> 2.0) 13 | websocket-driver (>= 0.6.1) 14 | actionmailer (5.2.3) 15 | actionpack (= 5.2.3) 16 | actionview (= 5.2.3) 17 | activejob (= 5.2.3) 18 | mail (~> 2.5, >= 2.5.4) 19 | rails-dom-testing (~> 2.0) 20 | actionpack (5.2.3) 21 | actionview (= 5.2.3) 22 | activesupport (= 5.2.3) 23 | rack (~> 2.0) 24 | rack-test (>= 0.6.3) 25 | rails-dom-testing (~> 2.0) 26 | rails-html-sanitizer (~> 1.0, >= 1.0.2) 27 | actionview (5.2.3) 28 | activesupport (= 5.2.3) 29 | builder (~> 3.1) 30 | erubi (~> 1.4) 31 | rails-dom-testing (~> 2.0) 32 | rails-html-sanitizer (~> 1.0, >= 1.0.3) 33 | activejob (5.2.3) 34 | activesupport (= 5.2.3) 35 | globalid (>= 0.3.6) 36 | activemodel (5.2.3) 37 | activesupport (= 5.2.3) 38 | activerecord (5.2.3) 39 | activemodel (= 5.2.3) 40 | activesupport (= 5.2.3) 41 | arel (>= 9.0) 42 | activestorage (5.2.3) 43 | actionpack (= 5.2.3) 44 | activerecord (= 5.2.3) 45 | marcel (~> 0.3.1) 46 | activesupport (5.2.3) 47 | concurrent-ruby (~> 1.0, >= 1.0.2) 48 | i18n (>= 0.7, < 2) 49 | minitest (~> 5.1) 50 | tzinfo (~> 1.1) 51 | arel (9.0.0) 52 | ast (2.4.0) 53 | builder (3.2.3) 54 | concurrent-ruby (1.1.5) 55 | crass (1.0.4) 56 | database_cleaner (1.7.0) 57 | diff-lcs (1.3) 58 | erubi (1.8.0) 59 | factory_bot (5.0.2) 60 | activesupport (>= 4.2.0) 61 | globalid (0.4.2) 62 | activesupport (>= 4.2.0) 63 | i18n (1.6.0) 64 | concurrent-ruby (~> 1.0) 65 | jaro_winkler (1.5.3) 66 | loofah (2.2.3) 67 | crass (~> 1.0.2) 68 | nokogiri (>= 1.5.9) 69 | mail (2.7.1) 70 | mini_mime (>= 0.1.1) 71 | marcel (0.3.3) 72 | mimemagic (~> 0.3.2) 73 | method_source (0.9.2) 74 | mimemagic (0.3.3) 75 | mini_mime (1.0.2) 76 | mini_portile2 (2.4.0) 77 | minitest (5.11.3) 78 | nio4r (2.5.2) 79 | nokogiri (1.10.3) 80 | mini_portile2 (~> 2.4.0) 81 | parallel (1.17.0) 82 | parser (2.6.4.1) 83 | ast (~> 2.4.0) 84 | pg (1.2.3) 85 | rack (2.0.7) 86 | rack-test (1.1.0) 87 | rack (>= 1.0, < 3) 88 | rails (5.2.3) 89 | actioncable (= 5.2.3) 90 | actionmailer (= 5.2.3) 91 | actionpack (= 5.2.3) 92 | actionview (= 5.2.3) 93 | activejob (= 5.2.3) 94 | activemodel (= 5.2.3) 95 | activerecord (= 5.2.3) 96 | activestorage (= 5.2.3) 97 | activesupport (= 5.2.3) 98 | bundler (>= 1.3.0) 99 | railties (= 5.2.3) 100 | sprockets-rails (>= 2.0.0) 101 | rails-dom-testing (2.0.3) 102 | activesupport (>= 4.2.0) 103 | nokogiri (>= 1.6) 104 | rails-html-sanitizer (1.0.4) 105 | loofah (~> 2.2, >= 2.2.2) 106 | railties (5.2.3) 107 | actionpack (= 5.2.3) 108 | activesupport (= 5.2.3) 109 | method_source 110 | rake (>= 0.8.7) 111 | thor (>= 0.19.0, < 2.0) 112 | rainbow (3.0.0) 113 | rake (12.3.2) 114 | rspec-core (3.8.0) 115 | rspec-support (~> 3.8.0) 116 | rspec-expectations (3.8.3) 117 | diff-lcs (>= 1.2.0, < 2.0) 118 | rspec-support (~> 3.8.0) 119 | rspec-mocks (3.8.0) 120 | diff-lcs (>= 1.2.0, < 2.0) 121 | rspec-support (~> 3.8.0) 122 | rspec-rails (3.8.2) 123 | actionpack (>= 3.0) 124 | activesupport (>= 3.0) 125 | railties (>= 3.0) 126 | rspec-core (~> 3.8.0) 127 | rspec-expectations (~> 3.8.0) 128 | rspec-mocks (~> 3.8.0) 129 | rspec-support (~> 3.8.0) 130 | rspec-support (3.8.0) 131 | rubocop (0.74.0) 132 | jaro_winkler (~> 1.5.1) 133 | parallel (~> 1.10) 134 | parser (>= 2.6) 135 | rainbow (>= 2.2.2, < 4.0) 136 | ruby-progressbar (~> 1.7) 137 | unicode-display_width (>= 1.4.0, < 1.7) 138 | ruby-progressbar (1.10.1) 139 | sprockets (3.7.2) 140 | concurrent-ruby (~> 1.0) 141 | rack (> 1, < 3) 142 | sprockets-rails (3.2.1) 143 | actionpack (>= 4.0) 144 | activesupport (>= 4.0) 145 | sprockets (>= 3.0.0) 146 | sqlite3 (1.4.1) 147 | thor (0.20.3) 148 | thread_safe (0.3.6) 149 | tzinfo (1.2.5) 150 | thread_safe (~> 0.1) 151 | unicode-display_width (1.6.0) 152 | websocket-driver (0.7.1) 153 | websocket-extensions (>= 0.1.0) 154 | websocket-extensions (0.1.4) 155 | 156 | PLATFORMS 157 | ruby 158 | 159 | DEPENDENCIES 160 | database_cleaner 161 | factory_bot 162 | jsonapi-scopes! 163 | pg 164 | rspec-rails 165 | rubocop 166 | sqlite3 167 | 168 | BUNDLED WITH 169 | 2.0.2 170 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | MIT License 3 | 4 | Copyright (c) 2019 Guillaume Briday 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/guillaumebriday) 2 | ![](https://github.com/guillaumebriday/jsonapi-scopes/workflows/Lint/badge.svg) 3 | ![](https://github.com/guillaumebriday/jsonapi-scopes/workflows/Test/badge.svg) 4 | [![](https://img.shields.io/gem/dt/jsonapi-scopes.svg)](https://rubygems.org/gems/jsonapi-scopes) 5 | [![](https://img.shields.io/gem/v/jsonapi-scopes.svg)](https://rubygems.org/gems/jsonapi-scopes) 6 | [![](https://img.shields.io/github/license/guillaumebriday/jsonapi-scopes.svg)](https://github.com/guillaumebriday/jsonapi-scopes) 7 | 8 | # Jsonapi::Scopes 9 | This gem provides a set of methods which allows you to include, filter and sort an ActiveRecord relation based on a request. It's built to be a simple, robust and scalable system. It follows the [JSON:API specification](https://jsonapi.org/) as closely as possible. 10 | 11 | It's also an unopinionated solution to help you follow the `JSON:API specification`. It doesn't care about how you want to handle the results. 12 | 13 | Moreover, it integrates seamlessly into your Rails application while not being a full library. 14 | 15 | ## Installation 16 | Add this line to your application's Gemfile: 17 | 18 | ```ruby 19 | gem 'jsonapi-scopes' 20 | ``` 21 | 22 | And then execute: 23 | ```bash 24 | $ bundle 25 | ``` 26 | 27 | ## Usage 28 | 29 | ### Filter 30 | This gem supports [filtering](https://jsonapi.org/format/#fetching-filtering). 31 | 32 | The gem add a `filter` method to define public scopes. 33 | It acts as a regular scope. 34 | 35 | ```ruby 36 | class Contact < ActiveRecord::Base 37 | include Jsonapi::Filter 38 | 39 | # Respond to `apply_filter` 40 | filter :first_name, ->(value) { 41 | where(first_name: value) 42 | } 43 | 44 | # Do NOT respond to `apply_filter` 45 | scope :last_name, ->(value) { 46 | where(last_name: value) 47 | } 48 | end 49 | ``` 50 | 51 | You can use `apply_filter` in your controller to use the scopes defined with the previous `filter` method: 52 | 53 | ```ruby 54 | class ContactsController < ApplicationController 55 | def index 56 | @contacts = Contact.apply_filter(params) 57 | end 58 | end 59 | ``` 60 | 61 | Then you can hit `/contacts?filter[first_name]=Bruce` to filter contacts where the first name exactly match `Bruce`. 62 | 63 | You can specify multiple matching filter values by passing a comma separated list of values: `/contacts?filter[first_name]=Bruce,Peter` will returns contacts where the first name exactly match `Bruce` or `Peter`. 64 | 65 | But `/contacts?filter[last_name]=Wayne` will be completely ignored. 66 | 67 | ### Sorting 68 | This gem supports [sorting](https://jsonapi.org/format/#fetching-sorting). 69 | 70 | The gem add `default_sort` and `sortable_fields` methods to control sort options. They can be overridden in controllers. 71 | 72 | ```ruby 73 | class Contact < ActiveRecord::Base 74 | include Jsonapi::Sort 75 | 76 | sortable_fields :lastname, :firstname # List of allowed attributes 77 | default_sort lastname: :desc, firstname: :asc # default hash with attributes and directions 78 | end 79 | ``` 80 | 81 | You can use `apply_sort` in your controller: 82 | 83 | ```ruby 84 | class ContactsController < ApplicationController 85 | def index 86 | @contacts = Contact.apply_sort(params) 87 | @contacts = Contact.apply_sort # to only apply default sort 88 | end 89 | end 90 | ``` 91 | 92 | `apply_sort` accepts a second parameter to override data set with `sortable_fields` and `default_sort` for a specific controller. 93 | ```ruby 94 | class ContactsController < ApplicationController 95 | def index 96 | @contacts = Contact.apply_sort(params, allowed: :full_name, default: { full_name: :desc }) 97 | # Or @contacts = Contact.apply_sort(params, allowed: [:lastname, :full_name], default: { full_name: :desc }) 98 | end 99 | end 100 | ``` 101 | 102 | Then you can hit `/contacts?sort=lastname` to sort contacts by lastname. 103 | 104 | Or use negative sort `/contacts?sort=-firstname` to sort by firstname in `desc` direction. 105 | 106 | You can even combine multiple sort `/contacts?sort=lastname,-firstname` 107 | 108 | 109 | ### Included relationships 110 | This gem supports [request include params](https://jsonapi.org/format/#fetching-includes). It's very useful when you need to load related resources on client side. 111 | 112 | ```ruby 113 | class Post < ActiveRecord::Base 114 | include Jsonapi::Include 115 | 116 | has_many :comments 117 | belongs_to :author 118 | 119 | allowed_includes 'comments', 'author.posts' # List of allowed includes 120 | end 121 | ``` 122 | 123 | You can use `apply_include` in your controller: 124 | 125 | ```ruby 126 | class PostsController < ApplicationController 127 | def index 128 | @posts = Post.apply_include(params) 129 | end 130 | end 131 | ``` 132 | 133 | `apply_include` accepts a second parameter to override data set with `allowed_includes` for a specific controller. 134 | ```ruby 135 | class PostsController < ApplicationController 136 | def index 137 | @posts = Post.apply_include(params, allowed: 'comments') # to allow only comments. 138 | # Or @posts = Post.apply_include(params, allowed: ['comments', 'author']) 139 | end 140 | end 141 | ``` 142 | 143 | Then you can hit `/posts?include=comments`. You can even combine multiple includes like `/posts?include=comments,author`. 144 | 145 | The gem only handle `include` on the ActiveRecord level. If you want to serialize the data, you must do it in your controller. 146 | 147 | #### Nested relationships 148 | 149 | You can load nested relationships using the dot `.` notation: 150 | 151 | `/posts?include=author.posts`. 152 | 153 | ### Rescuing a Bad Request in Rails 154 | 155 | Jsonapi::scope raises a `Jsonapi::InvalidAttributeError` you can [rescue_from](https://guides.rubyonrails.org/action_controller_overview.html#rescue-from) in your `ApplicationController`. 156 | 157 | If you want to follow the specification, you **must** respond with a `400 Bad Request`. 158 | 159 | ```ruby 160 | class ApplicationController < ActionController::Base 161 | rescue_from Jsonapi::InvalidAttributeError, with: :json_api_bad_request 162 | 163 | private 164 | 165 | def json_api_bad_request(exception) 166 | render json: { error: exception.message }, status: :bad_request 167 | end 168 | end 169 | ``` 170 | 171 | ## Contributing 172 | Do not hesitate to contribute to the project by adapting or adding features ! Bug reports or pull requests are welcome. 173 | 174 | ## Credits 175 | 176 | Inspired by: 177 | 178 | + [https://github.com/stefatkins/rails-starter-api](https://github.com/stefatkins/rails-starter-api) 179 | + [https://github.com/cerebris/jsonapi-resources](https://github.com/cerebris/jsonapi-resources) 180 | 181 | ## License 182 | The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). 183 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | begin 4 | require 'bundler/setup' 5 | rescue LoadError 6 | puts 'You must `gem install bundler` and `bundle install` to run rake tasks' 7 | end 8 | 9 | require 'rdoc/task' 10 | 11 | RDoc::Task.new(:rdoc) do |rdoc| 12 | rdoc.rdoc_dir = 'rdoc' 13 | rdoc.title = 'Jsonapi::Scopes' 14 | rdoc.options << '--line-numbers' 15 | rdoc.rdoc_files.include('README.md') 16 | rdoc.rdoc_files.include('lib/**/*.rb') 17 | end 18 | 19 | require 'bundler/gem_tasks' 20 | 21 | require 'rake/testtask' 22 | 23 | Rake::TestTask.new(:test) do |t| 24 | t.libs << 'test' 25 | t.pattern = 'test/**/*_test.rb' 26 | t.verbose = false 27 | end 28 | 29 | task default: :test 30 | -------------------------------------------------------------------------------- /bin/test: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | $LOAD_PATH << File.expand_path('../test', __dir__) 5 | 6 | require 'bundler/setup' 7 | require 'rails/plugin/test' 8 | -------------------------------------------------------------------------------- /jsonapi-scopes.gemspec: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | $LOAD_PATH.push File.expand_path('lib', __dir__) 4 | 5 | # Maintain your gem's version: 6 | require 'jsonapi/scopes/version' 7 | 8 | # Describe your gem and declare its dependencies: 9 | Gem::Specification.new do |spec| 10 | spec.name = 'jsonapi-scopes' 11 | spec.version = Jsonapi::Scopes::VERSION 12 | spec.authors = ['Guillaume Briday'] 13 | spec.email = ['guillaumebriday@gmail.com'] 14 | spec.homepage = 'https://github.com/guillaumebriday/jsonapi-scopes' 15 | spec.summary = 'This gem allows you to filter and sort an ActiveRecord relation based on a request, following the JSON:API specification as closely as possible.' 16 | spec.license = 'MIT' 17 | 18 | # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host' 19 | # to allow pushing to a single host or delete this section to allow pushing to any host. 20 | # if spec.respond_to?(:metadata) 21 | # spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'" 22 | # else 23 | # raise "RubyGems 2.0 or newer is required to protect against " \ 24 | # "public gem pushes." 25 | # end 26 | 27 | spec.files = Dir['{app,config,db,lib}/**/*', 'LICENSE', 'Rakefile', 'README.md'] 28 | 29 | spec.add_dependency 'rails' 30 | 31 | spec.add_development_dependency 'sqlite3' 32 | end 33 | -------------------------------------------------------------------------------- /lib/jsonapi/exceptions.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Jsonapi 4 | class Error < StandardError; end 5 | 6 | class InvalidAttributeError < Error 7 | def initialize(message) 8 | super(message) 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /lib/jsonapi/scopes.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'jsonapi/exceptions' 4 | require 'jsonapi/scopes/filters' 5 | require 'jsonapi/scopes/sorts' 6 | require 'jsonapi/scopes/includes' 7 | -------------------------------------------------------------------------------- /lib/jsonapi/scopes/filters.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Jsonapi 4 | module Filter 5 | extend ActiveSupport::Concern 6 | 7 | included do 8 | @filters ||= [] 9 | end 10 | 11 | module ClassMethods 12 | def filter(name, *args) 13 | scope(name, *args) 14 | @filters << name 15 | end 16 | 17 | def apply_filter(params) 18 | records = all 19 | filtering_params = params.dig(:filter) || {} 20 | 21 | filtering_params.each do |key, value| 22 | value = value.to_s.split(',').reject(&:blank?) if value.include?(',') 23 | 24 | raise InvalidAttributeError, "#{key} is not valid as filter attribute." unless @filters.include?(key.to_sym) 25 | 26 | records = records.public_send(key, value) 27 | end 28 | 29 | records 30 | end 31 | end 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /lib/jsonapi/scopes/includes.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Jsonapi 4 | module Include 5 | extend ActiveSupport::Concern 6 | 7 | included do 8 | @allowed_includes ||= [] 9 | end 10 | 11 | module ClassMethods 12 | def allowed_includes(*fields) 13 | @allowed_includes = fields 14 | end 15 | 16 | def apply_include(params = {}, options = { allowed: [] }) 17 | records = all 18 | fields = params.dig(:include).to_s 19 | 20 | return records if fields.blank? 21 | 22 | allowed_fields = (Array.wrap(options[:allowed]).presence || @allowed_includes).map(&:to_s) 23 | 24 | fields.split(',').each do |field| 25 | raise InvalidAttributeError, "#{field} is not valid as include attribute." unless allowed_fields.include?(field) 26 | end 27 | 28 | records.includes(convert_includes_as_hash(fields)) 29 | end 30 | 31 | private 32 | 33 | def convert_includes_as_hash(includes) 34 | includes.split(',').map(&:squish).each_with_object({}) do |value, hash| 35 | params = value.split('.') 36 | key = params.first.to_sym 37 | hash[key] ||= {} 38 | 39 | next if params.size <= 1 40 | 41 | remaining_fields = params[1..-1].join('.') 42 | 43 | hash[key].merge!(convert_includes_as_hash(remaining_fields)) 44 | end 45 | end 46 | end 47 | end 48 | end 49 | -------------------------------------------------------------------------------- /lib/jsonapi/scopes/sorts.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Jsonapi 4 | module Sort 5 | extend ActiveSupport::Concern 6 | 7 | included do 8 | @sortable_fields ||= [] 9 | @default_sort ||= {} 10 | end 11 | 12 | module ClassMethods 13 | def default_sort(sort) 14 | @default_sort = sort 15 | end 16 | 17 | def sortable_fields(*fields) 18 | @sortable_fields = fields 19 | end 20 | 21 | def apply_sort(params = {}, options = { allowed: [], default: {} }) 22 | fields = params.dig(:sort) 23 | 24 | allowed_fields = (Array.wrap(options[:allowed]).presence || @sortable_fields).map(&:to_sym) 25 | default_order = (options[:default].presence || @default_sort).transform_keys(&:to_sym) 26 | ordered_fields = convert_to_ordered_hash(fields) 27 | 28 | ordered_fields.each do |field, _| 29 | raise InvalidAttributeError, "#{field} is not valid as sort attribute." unless allowed_fields.include?(field) 30 | end 31 | 32 | order = ordered_fields.presence || default_order 33 | 34 | self.order(order) 35 | end 36 | 37 | private 38 | 39 | def convert_to_ordered_hash(fields) 40 | fields = fields.to_s.split(',').map(&:squish) 41 | 42 | fields.each_with_object({}) do |field, hash| 43 | if field.start_with?('-') 44 | field = field[1..-1] 45 | hash[field] = :desc 46 | else 47 | hash[field] = :asc 48 | end 49 | end.transform_keys(&:to_sym) 50 | end 51 | end 52 | end 53 | end 54 | -------------------------------------------------------------------------------- /lib/jsonapi/scopes/version.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Jsonapi 4 | module Scopes 5 | VERSION = '0.4.1' 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /test/dummy/.rspec: -------------------------------------------------------------------------------- 1 | --require spec_helper 2 | -------------------------------------------------------------------------------- /test/dummy/.ruby-version: -------------------------------------------------------------------------------- 1 | 2.6.3 2 | -------------------------------------------------------------------------------- /test/dummy/Rakefile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Add your own tasks in files placed in lib/tasks ending in .rake, 4 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 5 | 6 | require_relative 'config/application' 7 | 8 | Rails.application.load_tasks 9 | -------------------------------------------------------------------------------- /test/dummy/app/assets/config/manifest.js: -------------------------------------------------------------------------------- 1 | //= link_tree ../images 2 | //= link_directory ../stylesheets .css 3 | -------------------------------------------------------------------------------- /test/dummy/app/assets/images/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guillaumebriday/jsonapi-scopes/973d24e55222bda489a9399fc5a00011b0eab22d/test/dummy/app/assets/images/.keep -------------------------------------------------------------------------------- /test/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 | -------------------------------------------------------------------------------- /test/dummy/app/channels/application_cable/channel.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module ApplicationCable 4 | class Channel < ActionCable::Channel::Base 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /test/dummy/app/channels/application_cable/connection.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module ApplicationCable 4 | class Connection < ActionCable::Connection::Base 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /test/dummy/app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApplicationController < ActionController::Base 4 | end 5 | -------------------------------------------------------------------------------- /test/dummy/app/controllers/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guillaumebriday/jsonapi-scopes/973d24e55222bda489a9399fc5a00011b0eab22d/test/dummy/app/controllers/concerns/.keep -------------------------------------------------------------------------------- /test/dummy/app/helpers/application_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module ApplicationHelper 4 | end 5 | -------------------------------------------------------------------------------- /test/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 | -------------------------------------------------------------------------------- /test/dummy/app/jobs/application_job.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApplicationJob < ActiveJob::Base 4 | # Automatically retry jobs that encountered a deadlock 5 | # retry_on ActiveRecord::Deadlocked 6 | 7 | # Most jobs are safe to ignore if the underlying records are no longer available 8 | # discard_on ActiveJob::DeserializationError 9 | end 10 | -------------------------------------------------------------------------------- /test/dummy/app/mailers/application_mailer.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApplicationMailer < ActionMailer::Base 4 | default from: 'from@example.com' 5 | layout 'mailer' 6 | end 7 | -------------------------------------------------------------------------------- /test/dummy/app/models/application_record.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApplicationRecord < ActiveRecord::Base 4 | self.abstract_class = true 5 | end 6 | -------------------------------------------------------------------------------- /test/dummy/app/models/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guillaumebriday/jsonapi-scopes/973d24e55222bda489a9399fc5a00011b0eab22d/test/dummy/app/models/concerns/.keep -------------------------------------------------------------------------------- /test/dummy/app/models/contact.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Contact < ApplicationRecord 4 | include Jsonapi::Filter 5 | include Jsonapi::Sort 6 | 7 | has_many :users 8 | 9 | # Sorting 10 | sortable_fields :last_name 11 | default_sort last_name: :desc 12 | 13 | # Filters 14 | filter :first_name, ->(value) { where(first_name: value) } 15 | scope :last_name, ->(value) { where(last_name: value) } 16 | end 17 | -------------------------------------------------------------------------------- /test/dummy/app/models/post.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Post < ApplicationRecord 4 | belongs_to :user 5 | has_one :contact, through: :user 6 | end 7 | -------------------------------------------------------------------------------- /test/dummy/app/models/user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class User < ApplicationRecord 4 | include Jsonapi::Include 5 | 6 | belongs_to :contact 7 | has_many :posts 8 | 9 | allowed_includes 'contact', 'posts.contact.users', 'posts', 'posts.user' 10 | end 11 | -------------------------------------------------------------------------------- /test/dummy/app/views/layouts/application.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Dummy 5 | <%= csrf_meta_tags %> 6 | <%= csp_meta_tag %> 7 | 8 | <%= stylesheet_link_tag 'application', media: 'all' %> 9 | 10 | 11 | 12 | <%= yield %> 13 | 14 | 15 | -------------------------------------------------------------------------------- /test/dummy/app/views/layouts/mailer.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | -------------------------------------------------------------------------------- /test/dummy/app/views/layouts/mailer.text.erb: -------------------------------------------------------------------------------- 1 | <%= yield %> 2 | -------------------------------------------------------------------------------- /test/dummy/bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | APP_PATH = File.expand_path('../config/application', __dir__) 5 | require_relative '../config/boot' 6 | require 'rails/commands' 7 | -------------------------------------------------------------------------------- /test/dummy/bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | require_relative '../config/boot' 5 | require 'rake' 6 | Rake.application.run 7 | -------------------------------------------------------------------------------- /test/dummy/bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | require 'fileutils' 5 | 6 | # path to your application root. 7 | APP_ROOT = File.expand_path('..', __dir__) 8 | 9 | def system!(*args) 10 | system(*args) || abort("\n== Command #{args} failed ==") 11 | end 12 | 13 | FileUtils.chdir APP_ROOT do 14 | # This script is a starting point to setup your application. 15 | # Add necessary setup steps to this file. 16 | 17 | puts '== Installing dependencies ==' 18 | system! 'gem install bundler --conservative' 19 | system('bundle check') || system!('bundle install') 20 | 21 | # puts "\n== Copying sample files ==" 22 | # unless File.exist?('config/database.yml') 23 | # FileUtils.cp 'config/database.yml.sample', 'config/database.yml' 24 | # end 25 | 26 | puts "\n== Preparing database ==" 27 | system! 'bin/rails db:setup' 28 | 29 | puts "\n== Removing old logs and tempfiles ==" 30 | system! 'bin/rails log:clear tmp:clear' 31 | 32 | puts "\n== Restarting application server ==" 33 | system! 'bin/rails restart' 34 | end 35 | -------------------------------------------------------------------------------- /test/dummy/bin/update: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | require 'fileutils' 5 | 6 | # path to your application root. 7 | APP_ROOT = File.expand_path('..', __dir__) 8 | 9 | def system!(*args) 10 | system(*args) || abort("\n== Command #{args} failed ==") 11 | end 12 | 13 | FileUtils.chdir APP_ROOT do 14 | # This script is a way to update your development environment automatically. 15 | # Add necessary update steps to this file. 16 | 17 | puts '== Installing dependencies ==' 18 | system! 'gem install bundler --conservative' 19 | system('bundle check') || system!('bundle install') 20 | 21 | puts "\n== Updating database ==" 22 | system! 'rails db:migrate' 23 | 24 | puts "\n== Removing old logs and tempfiles ==" 25 | system! 'rails log:clear tmp:clear' 26 | 27 | puts "\n== Restarting application server ==" 28 | system! 'rails restart' 29 | end 30 | -------------------------------------------------------------------------------- /test/dummy/config.ru: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # This file is used by Rack-based servers to start the application. 4 | 5 | require_relative 'config/environment' 6 | 7 | run Rails.application 8 | -------------------------------------------------------------------------------- /test/dummy/config/application.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative 'boot' 4 | 5 | require 'rails/all' 6 | 7 | Bundler.require(*Rails.groups) 8 | require 'jsonapi/scopes' 9 | 10 | module Dummy 11 | class Application < Rails::Application 12 | # Initialize configuration defaults for originally generated Rails version. 13 | config.load_defaults 5.2 14 | 15 | # Settings in config/environments/* take precedence over those specified here. 16 | # Application configuration can go into files in config/initializers 17 | # -- all .rb files in that directory are automatically loaded after loading 18 | # the framework and any gems in your application. 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /test/dummy/config/boot.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Set up gems listed in the Gemfile. 4 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../Gemfile', __dir__) 5 | 6 | require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) 7 | $LOAD_PATH.unshift File.expand_path('../../../lib', __dir__) 8 | -------------------------------------------------------------------------------- /test/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 | -------------------------------------------------------------------------------- /test/dummy/config/database.yml: -------------------------------------------------------------------------------- 1 | # SQLite version 3.x 2 | # gem install sqlite3 3 | # 4 | # Ensure the SQLite 3 gem is defined in your Gemfile 5 | # gem 'sqlite3' 6 | # 7 | default: &default 8 | adapter: sqlite3 9 | pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> 10 | timeout: 5000 11 | 12 | development: 13 | <<: *default 14 | database: db/development.sqlite3 15 | 16 | # Warning: The database defined as "test" will be erased and 17 | # re-generated from your development database when you run "rake". 18 | # Do not set this db to the same as development or production. 19 | test: 20 | <<: *default 21 | database: db/test.sqlite3 22 | 23 | production: 24 | <<: *default 25 | database: db/production.sqlite3 26 | -------------------------------------------------------------------------------- /test/dummy/config/environment.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Load the Rails application. 4 | require_relative 'application' 5 | 6 | # Initialize the Rails application. 7 | Rails.application.initialize! 8 | -------------------------------------------------------------------------------- /test/dummy/config/environments/development.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 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 on 7 | # every request. 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 an error on page load if there are pending migrations. 45 | config.active_record.migration_error = :page_load 46 | 47 | # Highlight code that triggered database queries in logs. 48 | config.active_record.verbose_query_logs = true 49 | 50 | # Debug mode disables concatenation and preprocessing of assets. 51 | # This option may cause significant delays in view rendering with a large 52 | # number of complex assets. 53 | config.assets.debug = true 54 | 55 | # Suppress logger output for asset requests. 56 | config.assets.quiet = true 57 | 58 | # Raises error for missing translations. 59 | # config.action_view.raise_on_missing_translations = true 60 | 61 | # Use an evented file watcher to asynchronously detect changes in source code, 62 | # routes, locales, etc. This feature depends on the listen gem. 63 | # config.file_watcher = ActiveSupport::EventedFileUpdateChecker 64 | end 65 | -------------------------------------------------------------------------------- /test/dummy/config/environments/production.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 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.action_controller.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 | # Use the lowest log level to ensure availability of diagnostic information 52 | # when problems arise. 53 | config.log_level = :debug 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 | # Use default logging formatter so that PID and timestamp are not suppressed. 79 | config.log_formatter = ::Logger::Formatter.new 80 | 81 | # Use a different logger for distributed setups. 82 | # require 'syslog/logger' 83 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 84 | 85 | if ENV['RAILS_LOG_TO_STDOUT'].present? 86 | logger = ActiveSupport::Logger.new(STDOUT) 87 | logger.formatter = config.log_formatter 88 | config.logger = ActiveSupport::TaggedLogging.new(logger) 89 | end 90 | 91 | # Do not dump schema after migrations. 92 | config.active_record.dump_schema_after_migration = false 93 | 94 | # Inserts middleware to perform automatic connection switching. 95 | # The `database_selector` hash is used to pass options to the DatabaseSelector 96 | # middleware. The `delay` is used to determine how long to wait after a write 97 | # to send a subsequent read to the primary. 98 | # 99 | # The `database_resolver` class is used by the middleware to determine which 100 | # database is appropriate to use based on the time delay. 101 | # 102 | # The `database_resolver_context` class is used by the middleware to set 103 | # timestamps for the last write to the primary. The resolver uses the context 104 | # class timestamps to determine how long to wait before reading from the 105 | # replica. 106 | # 107 | # By default Rails will store a last write timestamp in the session. The 108 | # DatabaseSelector middleware is designed as such you can define your own 109 | # strategy for connection switching and pass that into the middleware through 110 | # these configuration options. 111 | # config.active_record.database_selector = { delay: 2.seconds } 112 | # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver 113 | # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session 114 | end 115 | -------------------------------------------------------------------------------- /test/dummy/config/environments/test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # The test environment is used exclusively to run your application's 7 | # test suite. You never need to work with it otherwise. Remember that 8 | # your test database is "scratch space" for the test suite and is wiped 9 | # and recreated between test runs. Don't rely on the data there! 10 | config.cache_classes = true 11 | 12 | # Do not eager load code on boot. This avoids loading your whole application 13 | # just for the purpose of running a single test. If you are using a tool that 14 | # preloads Rails for running tests, you may have to set it to true. 15 | config.eager_load = false 16 | 17 | # Configure public file server for tests with Cache-Control for performance. 18 | config.public_file_server.enabled = true 19 | config.public_file_server.headers = { 20 | 'Cache-Control' => "public, max-age=#{1.hour.to_i}" 21 | } 22 | 23 | # Show full error reports and disable caching. 24 | config.consider_all_requests_local = true 25 | config.action_controller.perform_caching = false 26 | config.cache_store = :null_store 27 | 28 | # Raise exceptions instead of rendering exception templates. 29 | config.action_dispatch.show_exceptions = false 30 | 31 | # Disable request forgery protection in test environment. 32 | config.action_controller.allow_forgery_protection = false 33 | 34 | # Store uploaded files on the local file system in a temporary directory. 35 | config.active_storage.service = :test 36 | 37 | config.action_mailer.perform_caching = false 38 | 39 | # Tell Action Mailer not to deliver emails to the real world. 40 | # The :test delivery method accumulates sent emails in the 41 | # ActionMailer::Base.deliveries array. 42 | config.action_mailer.delivery_method = :test 43 | 44 | # Print deprecation notices to the stderr. 45 | config.active_support.deprecation = :stderr 46 | 47 | # Raises error for missing translations. 48 | # config.action_view.raise_on_missing_translations = true 49 | end 50 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/application_controller_renderer.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # ActiveSupport::Reloader.to_prepare do 6 | # ApplicationController.renderer.defaults.merge!( 7 | # http_host: 'example.org', 8 | # https: false 9 | # ) 10 | # end 11 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/assets.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # Version of your assets, change this if you want to expire all your assets. 6 | Rails.application.config.assets.version = '1.0' 7 | 8 | # Add additional assets to the asset load path. 9 | # Rails.application.config.assets.paths << Emoji.images_path 10 | 11 | # Precompile additional assets. 12 | # application.js, application.css, and all non-JS/CSS in the app/assets 13 | # folder are already added. 14 | # Rails.application.config.assets.precompile += %w( admin.js admin.css ) 15 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 6 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } 7 | 8 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 9 | # Rails.backtrace_cleaner.remove_silencers! 10 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/content_security_policy.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # Define an application-wide content security policy 6 | # For further information see the following documentation 7 | # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy 8 | 9 | # Rails.application.config.content_security_policy do |policy| 10 | # policy.default_src :self, :https 11 | # policy.font_src :self, :https, :data 12 | # policy.img_src :self, :https, :data 13 | # policy.object_src :none 14 | # policy.script_src :self, :https 15 | # policy.style_src :self, :https 16 | 17 | # # Specify URI for violation reports 18 | # # policy.report_uri "/csp-violation-report-endpoint" 19 | # end 20 | 21 | # If you are using UJS then enable automatic nonce generation 22 | # Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) } 23 | 24 | # Report CSP violations to a specified URI 25 | # For further information see the following documentation: 26 | # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only 27 | # Rails.application.config.content_security_policy_report_only = true 28 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/cookies_serializer.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # Specify a serializer for the signed and encrypted cookie jars. 6 | # Valid options are :json, :marshal, and :hybrid. 7 | Rails.application.config.action_dispatch.cookies_serializer = :json 8 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # Configure sensitive parameters which will be filtered from the log file. 6 | Rails.application.config.filter_parameters += [:password] 7 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # Add new inflection rules using the following format. Inflections 6 | # are locale specific, and you may define rules for as many different 7 | # locales as you wish. All of these examples are active by default: 8 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 9 | # inflect.plural /^(ox)$/i, '\1en' 10 | # inflect.singular /^(ox)en/i, '\1' 11 | # inflect.irregular 'person', 'people' 12 | # inflect.uncountable %w( fish sheep ) 13 | # end 14 | 15 | # These inflection rules are supported but not enabled by default: 16 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 17 | # inflect.acronym 'RESTful' 18 | # end 19 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # Add new mime types for use in respond_to blocks: 6 | # Mime::Type.register "text/richtext", :rtf 7 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # This file contains settings for ActionController::ParamsWrapper which 6 | # is enabled by default. 7 | 8 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 9 | ActiveSupport.on_load(:action_controller) do 10 | wrap_parameters format: [:json] 11 | end 12 | 13 | # To enable root element in JSON for ActiveRecord objects. 14 | # ActiveSupport.on_load(:active_record) do 15 | # self.include_root_in_json = true 16 | # end 17 | -------------------------------------------------------------------------------- /test/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 | -------------------------------------------------------------------------------- /test/dummy/config/puma.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Puma can serve each request in a thread from an internal thread pool. 4 | # The `threads` method setting takes two numbers: a minimum and maximum. 5 | # Any libraries that use thread pools should be configured to match 6 | # the maximum value specified for Puma. Default is set to 5 threads for minimum 7 | # and maximum; this matches the default thread size of Active Record. 8 | # 9 | max_threads_count = ENV.fetch('RAILS_MAX_THREADS') { 5 } 10 | min_threads_count = ENV.fetch('RAILS_MIN_THREADS') { max_threads_count } 11 | threads min_threads_count, max_threads_count 12 | 13 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000. 14 | # 15 | port ENV.fetch('PORT') { 3000 } 16 | 17 | # Specifies the `environment` that Puma will run in. 18 | # 19 | environment ENV.fetch('RAILS_ENV') { 'development' } 20 | 21 | # Specifies the number of `workers` to boot in clustered mode. 22 | # Workers are forked web server processes. If using threads and workers together 23 | # the concurrency of the application would be max `threads` * `workers`. 24 | # Workers do not work on JRuby or Windows (both of which do not support 25 | # processes). 26 | # 27 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 } 28 | 29 | # Use the `preload_app!` method when specifying a `workers` number. 30 | # This directive tells Puma to first boot the application and load code 31 | # before forking the application. This takes advantage of Copy On Write 32 | # process behavior so workers use less memory. 33 | # 34 | # preload_app! 35 | 36 | # Allow puma to be restarted by `rails restart` command. 37 | plugin :tmp_restart 38 | -------------------------------------------------------------------------------- /test/dummy/config/routes.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.routes.draw do 4 | # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html 5 | end 6 | -------------------------------------------------------------------------------- /test/dummy/config/spring.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Spring.watch( 4 | '.ruby-version', 5 | '.rbenv-vars', 6 | 'tmp/restart.txt', 7 | 'tmp/caching-dev.txt' 8 | ) 9 | -------------------------------------------------------------------------------- /test/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 | -------------------------------------------------------------------------------- /test/dummy/db/migrate/20190511203334_create_contacts.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class CreateContacts < ActiveRecord::Migration[5.2] 4 | def change 5 | create_table :contacts do |t| 6 | t.string :last_name 7 | t.string :first_name 8 | t.integer :age 9 | 10 | t.timestamps 11 | end 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /test/dummy/db/migrate/20190916201953_create_users.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class CreateUsers < ActiveRecord::Migration[5.2] 4 | def change 5 | create_table :users do |t| 6 | t.string :name 7 | t.references :contact 8 | 9 | t.timestamps 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /test/dummy/db/schema.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # This file is auto-generated from the current state of the database. Instead 4 | # of editing this file, please use the migrations feature of Active Record to 5 | # incrementally modify your database, and then regenerate this schema definition. 6 | # 7 | # Note that this schema.rb definition is the authoritative source for your 8 | # database schema. If you need to create the application database on another 9 | # system, you should be using db:schema:load, not running all the migrations 10 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 11 | # you'll amass, the slower it'll run and the greater likelihood for issues). 12 | # 13 | # It's strongly recommended that you check this file into your version control system. 14 | 15 | ActiveRecord::Schema.define(version: 20_190_916_202_107) do 16 | create_table 'contacts', force: :cascade do |t| 17 | t.string 'last_name' 18 | t.string 'first_name' 19 | t.integer 'age' 20 | t.datetime 'created_at', null: false 21 | t.datetime 'updated_at', null: false 22 | end 23 | 24 | create_table 'posts', force: :cascade do |t| 25 | t.string 'title' 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_posts_on_user_id' 30 | end 31 | 32 | create_table 'users', force: :cascade do |t| 33 | t.string 'name' 34 | t.integer 'contact_id' 35 | t.datetime 'created_at', null: false 36 | t.datetime 'updated_at', null: false 37 | t.index ['contact_id'], name: 'index_users_on_contact_id' 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /test/dummy/lib/assets/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guillaumebriday/jsonapi-scopes/973d24e55222bda489a9399fc5a00011b0eab22d/test/dummy/lib/assets/.keep -------------------------------------------------------------------------------- /test/dummy/log/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guillaumebriday/jsonapi-scopes/973d24e55222bda489a9399fc5a00011b0eab22d/test/dummy/log/.keep -------------------------------------------------------------------------------- /test/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 | -------------------------------------------------------------------------------- /test/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 | -------------------------------------------------------------------------------- /test/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 | -------------------------------------------------------------------------------- /test/dummy/public/apple-touch-icon-precomposed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guillaumebriday/jsonapi-scopes/973d24e55222bda489a9399fc5a00011b0eab22d/test/dummy/public/apple-touch-icon-precomposed.png -------------------------------------------------------------------------------- /test/dummy/public/apple-touch-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guillaumebriday/jsonapi-scopes/973d24e55222bda489a9399fc5a00011b0eab22d/test/dummy/public/apple-touch-icon.png -------------------------------------------------------------------------------- /test/dummy/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guillaumebriday/jsonapi-scopes/973d24e55222bda489a9399fc5a00011b0eab22d/test/dummy/public/favicon.ico -------------------------------------------------------------------------------- /test/dummy/spec/factories/contacts.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | FactoryBot.define do 4 | factory :contact do 5 | first_name { 'Anakin' } 6 | last_name { 'Skywalker' } 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /test/dummy/spec/factories/posts.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | FactoryBot.define do 4 | factory :post do 5 | title { 'Anakin' } 6 | user 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /test/dummy/spec/factories/users.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | FactoryBot.define do 4 | factory :user do 5 | name { 'Anakin' } 6 | contact 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /test/dummy/spec/models/contact_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'rails_helper' 4 | 5 | RSpec.describe Contact, type: :model do 6 | describe 'instances_method' do 7 | context 'when filterable' do 8 | it 'responds to filter' do 9 | expect(Contact).to respond_to(:filter) 10 | end 11 | 12 | it 'responds to apply_filter' do 13 | expect(Contact).to respond_to(:apply_filter) 14 | end 15 | end 16 | 17 | context 'when sortable' do 18 | it 'responds to apply_sort' do 19 | expect(Contact).to respond_to(:apply_sort) 20 | end 21 | 22 | it 'responds to sortable_fields' do 23 | expect(Contact).to respond_to(:sortable_fields) 24 | end 25 | 26 | it 'responds to default_sort' do 27 | expect(Contact).to respond_to(:default_sort) 28 | end 29 | end 30 | end 31 | 32 | describe '#apply_filter' do 33 | let!(:anakin) { create(:contact, first_name: 'Anakin', last_name: 'Skywalker') } 34 | let!(:harry) { create(:contact, first_name: 'Harry', last_name: 'Potter') } 35 | let!(:peter) { create(:contact, first_name: 'Peter', last_name: 'Parker') } 36 | 37 | context 'with valid params' do 38 | let(:valid_params) do 39 | { 40 | filter: { first_name: 'Anakin' } 41 | } 42 | end 43 | 44 | it 'filters by first_name' do 45 | expect(Contact.apply_filter(valid_params)).to include(anakin) 46 | expect(Contact.apply_filter(valid_params)).to_not include(harry) 47 | end 48 | 49 | it 'filters by multiple first_name' do 50 | valid_params = { 51 | filter: { first_name: 'Anakin,Harry' } 52 | } 53 | 54 | expect(Contact.apply_filter(valid_params)).to include(anakin, harry) 55 | expect(Contact.apply_filter(valid_params)).to_not include(peter) 56 | end 57 | end 58 | 59 | context 'with invalid params' do 60 | let(:invalid_params) do 61 | { 62 | filter: { last_name: 'Potter' } 63 | } 64 | end 65 | 66 | it 'raises an exception' do 67 | expect { Contact.apply_filter(invalid_params) }.to raise_exception(Jsonapi::InvalidAttributeError, 'last_name is not valid as filter attribute.') 68 | end 69 | end 70 | end 71 | 72 | describe '#apply_sort' do 73 | let!(:anakin) { create(:contact, first_name: 'Anakin', last_name: 'Skywalker') } 74 | let!(:harry) { create(:contact, first_name: 'Harry', last_name: 'Potter') } 75 | 76 | context 'with valid params' do 77 | it 'sorts by last_name' do 78 | valid_params = { sort: 'last_name' } 79 | expected_ids = Contact.order(:last_name).pluck(:id) 80 | not_expected_ids = Contact.order(last_name: :desc).pluck(:id) 81 | 82 | expect(Contact.apply_sort(valid_params).pluck(:id)).to eq(expected_ids) 83 | expect(Contact.apply_sort(valid_params).pluck(:id)).to_not eq(not_expected_ids) 84 | end 85 | 86 | it 'sorts by last_name desc' do 87 | valid_params = { sort: '-last_name' } 88 | expected_ids = Contact.order(last_name: :desc).pluck(:id) 89 | not_expected_ids = Contact.order(:last_name).pluck(:id) 90 | 91 | expect(Contact.apply_sort(valid_params).pluck(:id)).to eq(expected_ids) 92 | expect(Contact.apply_sort(valid_params).pluck(:id)).to_not eq(not_expected_ids) 93 | end 94 | end 95 | 96 | context 'with invalid params' do 97 | let(:anakin) { create(:contact, first_name: 'Anakin', last_name: 'Skywalker', age: 19) } 98 | let(:harry) { create(:contact, first_name: 'Harry', last_name: 'Potter', age: 13) } 99 | 100 | it 'raises an exception' do 101 | invalid_params = { sort: 'age' } 102 | 103 | expect { Contact.apply_sort(invalid_params) }.to raise_exception(Jsonapi::InvalidAttributeError, 'age is not valid as sort attribute.') 104 | end 105 | end 106 | end 107 | 108 | describe '#default_sort' do 109 | let!(:anakin) { create(:contact, first_name: 'Anakin', last_name: 'Skywalker') } 110 | let!(:harry) { create(:contact, first_name: 'Harry', last_name: 'Potter') } 111 | let!(:spiderman) { create(:contact, first_name: 'Peter', last_name: 'Parker') } 112 | 113 | it 'sorts by default params' do 114 | expected_ids = Contact.order(last_name: :desc).pluck(:id) 115 | not_expected_ids = Contact.order(:last_name).pluck(:id) 116 | 117 | expect(Contact.apply_sort.pluck(:id)).to eq(expected_ids) 118 | expect(Contact.apply_sort.pluck(:id)).to_not eq(not_expected_ids) 119 | end 120 | end 121 | end 122 | -------------------------------------------------------------------------------- /test/dummy/spec/models/user_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'rails_helper' 4 | 5 | RSpec.describe User, type: :model do 6 | describe 'instances_method' do 7 | it 'responds to apply_sort' do 8 | expect(User).to respond_to(:apply_include) 9 | end 10 | 11 | it 'responds to allowed_includes' do 12 | expect(User).to respond_to(:allowed_includes) 13 | end 14 | end 15 | 16 | describe '#apply_include' do 17 | let!(:contact) { create(:contact) } 18 | let!(:user) { create(:user, contact: contact) } 19 | let!(:posts) { create_list(:post, 3, user: user) } 20 | 21 | context 'with valid params' do 22 | let(:valid_params) do 23 | { 24 | include: 'contact,posts' 25 | } 26 | end 27 | 28 | it 'includes relationships' do 29 | users = User.apply_include(valid_params) 30 | expect(users.first.association(:contact)).to be_loaded 31 | expect(users.first.association(:posts)).to be_loaded 32 | end 33 | 34 | it 'includes sub relationships' do 35 | valid_params = { 36 | include: 'contact,posts.contact.users,posts.user' 37 | } 38 | 39 | users = User.apply_include(valid_params) 40 | expect(users.first.association(:contact)).to be_loaded 41 | expect(users.first.posts.first.association(:contact)).to be_loaded 42 | expect(users.first.posts.first.association(:user)).to be_loaded 43 | expect(users.first.posts.first.contact.association(:users)).to be_loaded 44 | end 45 | end 46 | 47 | context 'with custom allowed attributes' do 48 | let(:valid_params) do 49 | { 50 | include: 'posts.contact' 51 | } 52 | end 53 | 54 | it 'raises an error' do 55 | expect { User.apply_include(valid_params) }.to raise_exception(Jsonapi::InvalidAttributeError, 'posts.contact is not valid as include attribute.') 56 | end 57 | 58 | it 'includes sub relationships' do 59 | users = User.apply_include(valid_params, allowed: 'posts.contact') 60 | expect(users.first.posts.first.association(:contact)).to be_loaded 61 | end 62 | end 63 | 64 | context 'with invalid params' do 65 | let(:invalid_params) do 66 | { 67 | include: 'invalid' 68 | } 69 | end 70 | 71 | it 'raises an exception' do 72 | expect { User.apply_include(invalid_params) }.to raise_exception(Jsonapi::InvalidAttributeError, 'invalid is not valid as include attribute.') 73 | end 74 | end 75 | 76 | context 'with empty params' do 77 | let(:empty_params) do 78 | { 79 | include: '' 80 | } 81 | end 82 | 83 | it 'returns same collection' do 84 | expect(User.apply_include(empty_params).first).to eq(User.first) 85 | end 86 | end 87 | end 88 | 89 | describe '#convert_includes_as_hash' do 90 | it 'returns the correct hash' do 91 | expect(User.send(:convert_includes_as_hash, 'contact')).to eq(contact: {}) 92 | expect(User.send(:convert_includes_as_hash, 'contact,posts')).to eq(contact: {}, posts: {}) 93 | expect(User.send(:convert_includes_as_hash, 'contact,posts.user')).to eq(contact: {}, posts: { user: {} }) 94 | expect(User.send(:convert_includes_as_hash, 'contact,posts.user,posts.contact')).to eq(contact: {}, posts: { user: {}, contact: {} }) 95 | expect(User.send(:convert_includes_as_hash, 'contact,posts.user,posts.contact.users')).to eq(contact: {}, posts: { user: {}, contact: { users: {} } }) 96 | expect(User.send(:convert_includes_as_hash, 'contact,posts.user,posts.contact.users,contact.users')).to eq(contact: { users: {} }, posts: { user: {}, contact: { users: {} } }) 97 | expect(User.send(:convert_includes_as_hash, 'contact,posts.user,posts.contact,posts.user.contacts')).to eq(contact: {}, posts: { user: { contacts: {} }, contact: {} }) 98 | expect(User.send(:convert_includes_as_hash, '')).to eq({}) 99 | end 100 | end 101 | end 102 | -------------------------------------------------------------------------------- /test/dummy/spec/rails_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # This file is copied to spec/ when you run 'rails generate rspec:install' 4 | require 'spec_helper' 5 | ENV['RAILS_ENV'] ||= 'test' 6 | require File.expand_path('../config/environment', __dir__) 7 | # Prevent database truncation if the environment is production 8 | abort('The Rails environment is running in production mode!') if Rails.env.production? 9 | require 'rspec/rails' 10 | # Add additional requires below this line. Rails is not loaded until this point! 11 | 12 | # Requires supporting ruby files with custom matchers and macros, etc, in 13 | # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are 14 | # run as spec files by default. This means that files in spec/support that end 15 | # in _spec.rb will both be required and run as specs, causing the specs to be 16 | # run twice. It is recommended that you do not name files matching this glob to 17 | # end with _spec.rb. You can configure this pattern with the --pattern 18 | # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. 19 | # 20 | # The following line is provided for convenience purposes. It has the downside 21 | # of increasing the boot-up time by auto-requiring all files in the support 22 | # directory. Alternatively, in the individual `*_spec.rb` files, manually 23 | # require only the support files necessary. 24 | # 25 | Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f } 26 | 27 | # Checks for pending migrations and applies them before tests are run. 28 | # If you are not using ActiveRecord, you can remove these lines. 29 | begin 30 | ActiveRecord::Migration.maintain_test_schema! 31 | rescue ActiveRecord::PendingMigrationError => e 32 | puts e.to_s.strip 33 | exit 1 34 | end 35 | 36 | RSpec.configure do |config| 37 | config.include FactoryBot::Syntax::Methods 38 | 39 | config.before(:suite) do 40 | DatabaseCleaner.strategy = :transaction 41 | DatabaseCleaner.clean_with(:truncation) 42 | FactoryBot.find_definitions 43 | end 44 | 45 | config.around do |example| 46 | DatabaseCleaner.cleaning do 47 | example.run 48 | end 49 | end 50 | 51 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 52 | config.fixture_path = "#{::Rails.root}/spec/fixtures" 53 | 54 | # If you're not using ActiveRecord, or you'd prefer not to run each of your 55 | # examples within a transaction, remove the following line or assign false 56 | # instead of true. 57 | config.use_transactional_fixtures = true 58 | 59 | # RSpec Rails can automatically mix in different behaviours to your tests 60 | # based on their file location, for example enabling you to call `get` and 61 | # `post` in specs under `spec/controllers`. 62 | # 63 | # You can disable this behaviour by removing the line below, and instead 64 | # explicitly tag your specs with their type, e.g.: 65 | # 66 | # RSpec.describe UsersController, :type => :controller do 67 | # # ... 68 | # end 69 | # 70 | # The different available types are documented in the features, such as in 71 | # https://relishapp.com/rspec/rspec-rails/docs 72 | config.infer_spec_type_from_file_location! 73 | 74 | # Filter lines from Rails gems in backtraces. 75 | config.filter_rails_from_backtrace! 76 | # arbitrary gems may also be filtered via: 77 | # config.filter_gems_from_backtrace("gem name") 78 | end 79 | -------------------------------------------------------------------------------- /test/dummy/spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # This file was generated by the `rspec --init` command. Conventionally, all 4 | # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. 5 | # The generated `.rspec` file contains `--require spec_helper` which will cause 6 | # this file to always be loaded, without a need to explicitly require it in any 7 | # files. 8 | # 9 | # Given that it is always loaded, you are encouraged to keep this file as 10 | # light-weight as possible. Requiring heavyweight dependencies from this file 11 | # will add to the boot time of your test suite on EVERY test run, even for an 12 | # individual file that may not need all of that loaded. Instead, consider making 13 | # a separate helper file that requires the additional dependencies and performs 14 | # the additional setup, and require it from the spec files that actually need 15 | # it. 16 | # 17 | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration 18 | RSpec.configure do |config| 19 | # rspec-expectations config goes here. You can use an alternate 20 | # assertion/expectation library such as wrong or the stdlib/minitest 21 | # assertions if you prefer. 22 | config.expect_with :rspec do |expectations| 23 | # This option will default to `true` in RSpec 4. It makes the `description` 24 | # and `failure_message` of custom matchers include text for helper methods 25 | # defined using `chain`, e.g.: 26 | # be_bigger_than(2).and_smaller_than(4).description 27 | # # => "be bigger than 2 and smaller than 4" 28 | # ...rather than: 29 | # # => "be bigger than 2" 30 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true 31 | end 32 | 33 | # rspec-mocks config goes here. You can use an alternate test double 34 | # library (such as bogus or mocha) by changing the `mock_with` option here. 35 | config.mock_with :rspec do |mocks| 36 | # Prevents you from mocking or stubbing a method that does not exist on 37 | # a real object. This is generally recommended, and will default to 38 | # `true` in RSpec 4. 39 | mocks.verify_partial_doubles = true 40 | end 41 | 42 | # This option will default to `:apply_to_host_groups` in RSpec 4 (and will 43 | # have no way to turn it off -- the option exists only for backwards 44 | # compatibility in RSpec 3). It causes shared context metadata to be 45 | # inherited by the metadata hash of host groups and examples, rather than 46 | # triggering implicit auto-inclusion in groups with matching metadata. 47 | config.shared_context_metadata_behavior = :apply_to_host_groups 48 | 49 | # The settings below are suggested to provide a good initial experience 50 | # with RSpec, but feel free to customize to your heart's content. 51 | # # This allows you to limit a spec run to individual examples or groups 52 | # # you care about by tagging them with `:focus` metadata. When nothing 53 | # # is tagged with `:focus`, all examples get run. RSpec also provides 54 | # # aliases for `it`, `describe`, and `context` that include `:focus` 55 | # # metadata: `fit`, `fdescribe` and `fcontext`, respectively. 56 | # config.filter_run_when_matching :focus 57 | # 58 | # # Allows RSpec to persist some state between runs in order to support 59 | # # the `--only-failures` and `--next-failure` CLI options. We recommend 60 | # # you configure your source control system to ignore this file. 61 | # config.example_status_persistence_file_path = "spec/examples.txt" 62 | # 63 | # # Limits the available syntax to the non-monkey patched syntax that is 64 | # # recommended. For more details, see: 65 | # # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ 66 | # # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ 67 | # # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode 68 | # config.disable_monkey_patching! 69 | # 70 | # # This setting enables warnings. It's recommended, but in some cases may 71 | # # be too noisy due to issues in dependencies. 72 | # config.warnings = true 73 | # 74 | # # Many RSpec users commonly either run the entire suite or an individual 75 | # # file, and it's useful to allow more verbose output when running an 76 | # # individual spec file. 77 | # if config.files_to_run.one? 78 | # # Use the documentation formatter for detailed output, 79 | # # unless a formatter has already been configured 80 | # # (e.g. via a command-line flag). 81 | # config.default_formatter = "doc" 82 | # end 83 | # 84 | # # Print the 10 slowest examples and example groups at the 85 | # # end of the spec run, to help surface which specs are running 86 | # # particularly slow. 87 | # config.profile_examples = 10 88 | # 89 | # # Run specs in random order to surface order dependencies. If you find an 90 | # # order dependency and want to debug it, you can fix the order by providing 91 | # # the seed, which is printed after each run. 92 | # # --seed 1234 93 | # config.order = :random 94 | # 95 | # # Seed global randomization in this process using the `--seed` CLI option. 96 | # # Setting this allows you to use `--seed` to deterministically reproduce 97 | # # test failures related to randomization by passing the same `--seed` value 98 | # # as the one that triggered the failure. 99 | # Kernel.srand config.seed 100 | end 101 | -------------------------------------------------------------------------------- /test/dummy/test/fixtures/contacts.yml: -------------------------------------------------------------------------------- 1 | # Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html 2 | 3 | # This model initially had no columns defined. If you add columns to the 4 | # model remove the '{}' from the fixture names and add the columns immediately 5 | # below each fixture, per the syntax in the comments below 6 | # 7 | batman: 8 | first_name: Bruce 9 | last_name: Wayne 10 | age: 41 11 | 12 | anakin: 13 | first_name: Anakin 14 | last_name: Skywalker 15 | age: 9 16 | -------------------------------------------------------------------------------- /test/dummy/test/models/contact_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require File.expand_path('../../../test_helper', __dir__) 4 | 5 | class ContactTest < ActiveSupport::TestCase 6 | # test "the truth" do 7 | # assert true 8 | # end 9 | end 10 | -------------------------------------------------------------------------------- /test/jsonapi/scopes_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | class Jsonapi::Scopes::Test < ActiveSupport::TestCase 6 | test 'truth' do 7 | assert_kind_of Module, Jsonapi::Scopes 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /test/test_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Configure Rails Environment 4 | ENV['RAILS_ENV'] = 'test' 5 | 6 | require_relative '../test/dummy/config/environment' 7 | ActiveRecord::Migrator.migrations_paths = [File.expand_path('../test/dummy/db/migrate', __dir__)] 8 | require 'rails/test_help' 9 | 10 | # Filter out the backtrace from minitest while preserving the one from other libraries. 11 | Minitest.backtrace_filter = Minitest::BacktraceFilter.new 12 | 13 | require 'rails/test_unit/reporter' 14 | Rails::TestUnitReporter.executable = 'bin/test' 15 | 16 | # Load fixtures from the engine 17 | if ActiveSupport::TestCase.respond_to?(:fixture_path=) 18 | ActiveSupport::TestCase.fixture_path = File.expand_path('fixtures', __dir__) 19 | ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path 20 | ActiveSupport::TestCase.file_fixture_path = ActiveSupport::TestCase.fixture_path + '/files' 21 | ActiveSupport::TestCase.fixtures :all 22 | end 23 | --------------------------------------------------------------------------------