act_as_jsonapi 0.1.2

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 3b66ec4025d3d67ed9b8e004a649098e95d3bf87a51e4be2aa0cd993fef86490
4
+ data.tar.gz: c83d9bf7ed1a77ea18e8b76b70ef5b7c9954bcfaf84991fed7bfebea471cf2b7
5
+ SHA512:
6
+ metadata.gz: 43bfc7efca48c8e84fb9b398d116cfa2b5e4b880115cc63674e7ec7f9be6f2da2340960c4b9a35b8f321b172ff006847621f902d7b175bdf3de4a347482941cb
7
+ data.tar.gz: b4832bc2cc42fac707f4fe81d06694fd29a5644f7c44c188ca6475adbff65b280800704126803993d373bd036600ab2b59c275267a30bb88d316dc10f561c1a2
@@ -0,0 +1,18 @@
1
+ name: Ruby
2
+
3
+ on: [push,pull_request]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v2
10
+ - name: Set up Ruby
11
+ uses: ruby/setup-ruby@v1
12
+ with:
13
+ ruby-version: 3.0.1
14
+ - name: Run the default task
15
+ run: |
16
+ gem install bundler -v 2.2.15
17
+ bundle install
18
+ bundle exec rake
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.4
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-03-13
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at lizzydw@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in act_as_jsonapi.gemspec
6
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 leizzer
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,152 @@
1
+ # ActAsJsonapi
2
+
3
+ Act as JSONAPI is a small and flexible gem on top of `jsonapi_serializer` and `pundit` gems.
4
+
5
+ By including Act as JSONAPI in your controllers you instantly
6
+ get all basic controller actions for the model and authorization checks.
7
+
8
+ Plus formatted responses with meta, links and pagination as in JSON:API documentation
9
+ and consistent error formatting.
10
+
11
+ You can override the model and serializer if the name of the controller doesn't match the model.
12
+ The json formatter and errors can be used separatly.
13
+
14
+ ## Installation
15
+
16
+ Add this line to your application's Gemfile:
17
+
18
+ ```ruby
19
+ gem 'act_as_jsonapi'
20
+ ```
21
+
22
+ And then execute:
23
+
24
+ $ bundle install
25
+
26
+ Or install it yourself as:
27
+
28
+ $ gem install act_as_jsonapi
29
+
30
+ ## Notes
31
+ Project isn't fully polished so there are some considerations to have while adding the gem to a project.
32
+
33
+ Notes:
34
+ - ActAsJsonapi assumes the project will use `pundnit`.
35
+ - Project needs to have gem `jsonapi-serializer` in Gemfile.
36
+ - Project needs some kinde of pagination gem like `kaminari` that adds the `#page` method.
37
+ - Project needs to respond to `current_user` for Pundit. Gem like `devise` can be used.
38
+
39
+ ## Usage
40
+
41
+ To get all actions, error handling and serialization at once. (Controller includes Formatter and JSONErrors)
42
+
43
+ This will give BooksController the methods `#index`, `#show`, `#update` and `#destroy`, with authorization checks.
44
+ The model and serializer are atomatically loaded based on the name of the controller and it expects that Rails
45
+ conventions were followed.
46
+ ```ruby
47
+ class BooksController < ApplicationController
48
+ include ActAsJsonapi::Controller
49
+ end
50
+ ```
51
+
52
+ If you want to include the just `render_json_api` method.
53
+ ```ruby
54
+ class BooksController < ApplicationController
55
+ include ActAsJsonapi::Formatter
56
+
57
+ def index
58
+ render_json_api BookSerializer.new(@books).serializable_hash
59
+ end
60
+ end
61
+ ```
62
+
63
+ Just the error handling
64
+ ```ruby
65
+ class BooksController < ApplicationController
66
+ include ActAsJsonapi::JSONErrors
67
+
68
+ def index
69
+ #your code...
70
+ render_error :unprocessable_entity, :err_workflow_update, 'my message'
71
+ end
72
+ end
73
+ ```
74
+
75
+ Using `rescue_errors` examples
76
+ ```ruby
77
+ class ApplicationController < ActionController::API
78
+ include ActAsJsonapi::JSONErrors
79
+
80
+ rescue_from ActionController::ParameterMissing, with: :render_bad_request
81
+ rescue_from ActionController::BadRequest, with: :render_bad_request
82
+ rescue_from ActiveRecord::RecordNotFound, with: :render_not_found
83
+ rescue_from Pundit::NotAuthorizedError, with: :render_forbidden
84
+ end
85
+ ```
86
+
87
+ ```ruby
88
+ class ApplicationController < ApplicationController
89
+ include ActAsJsonapi::JSONErrors
90
+
91
+ rescue_from ActiveRecord::RecordNotFound, :with => :err_record_not_found
92
+
93
+ private
94
+
95
+ def err_record_not_found(ex)
96
+ render_error :unprocessable_entity, :err_record_not_found, ex.message
97
+ end
98
+ end
99
+ ```
100
+
101
+ ## Overriding
102
+
103
+ `ActAsJsonapi::Controller` provides two handy class methods to change the model and/or serializer name.
104
+
105
+ ```ruby
106
+ class API::Inventory < ApplicationController
107
+ include ActAsJsonapi::Controller
108
+
109
+ model_set Book
110
+ serializer_set BookSerializer
111
+
112
+ #...
113
+ end
114
+ ```
115
+
116
+ Another common practice is to override the `_resource` and `_resources` methods
117
+
118
+ ```ruby
119
+ class BookController < ApplicationController
120
+ include ActAsJsonapi::Controller
121
+
122
+ #...
123
+
124
+ private
125
+
126
+ def _resource
127
+ @_resouce = #Complex query that returns one Book
128
+ end
129
+
130
+ def _resources
131
+ @_resouces = #Complex query that returns a collection of Books
132
+ end
133
+ end
134
+ ```
135
+
136
+ ## Development
137
+
138
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
139
+
140
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
141
+
142
+ ## Contributing
143
+
144
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/act_as_jsonapi. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/act_as_jsonapi/blob/master/CODE_OF_CONDUCT.md).
145
+
146
+ ## License
147
+
148
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
149
+
150
+ ## Code of Conduct
151
+
152
+ Everyone interacting in the ActAsJsonapi project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/act_as_jsonapi/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/act_as_jsonapi/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "act_as_jsonapi"
7
+ spec.version = ActAsJsonapi::VERSION
8
+ spec.authors = ["leizzer"]
9
+
10
+ spec.summary = "Light weight gem on top of `jsonapi_serializer` and `pundit` to keep controllers DRY"
11
+ spec.description = "Act as JSONAPI is a small and flexible gem on top of `jsonapi_serializer`. \
12
+ By including Act as JSONAPI in your controllers you instantly \
13
+ get all basic controller actions for the model. You can override the model and serializer if \
14
+ the name of the controller doesn't match the model. \
15
+ The json formatter and errors can be used separatly."
16
+ spec.homepage = "https://github.com/leizzer/act_as_jsonapi"
17
+ spec.license = "MIT"
18
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.4.0")
19
+
20
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
21
+
22
+ spec.metadata["homepage_uri"] = spec.homepage
23
+ spec.metadata["source_code_uri"] = "https://github.com/leizzer/act_as_jsonapi"
24
+ spec.metadata["changelog_uri"] = "https://github.com/leizzer/act_as_jsonapi/blob/main/CHANGELOG.md"
25
+
26
+ # Specify which files should be added to the gem when it is released.
27
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
28
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
29
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
30
+ end
31
+ spec.bindir = "exe"
32
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
33
+ spec.require_paths = ["lib"]
34
+
35
+
36
+ spec.add_development_dependency "rubocop", "~> 1.7"
37
+ spec.add_development_dependency "rspec", "~> 3.0"
38
+ spec.add_development_dependency "rake", "~> 13.0"
39
+
40
+ spec.add_dependency "jsonapi-serializer", "~> 2.2.0"
41
+ spec.add_dependency "activesupport", "~> 7.0"
42
+ spec.add_dependency "pundit", "~> 2.1"
43
+ end
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "act_as_jsonapi"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,189 @@
1
+ require "pundit"
2
+ require_relative 'formatter'
3
+ require_relative 'json_errors'
4
+
5
+ module ActAsJsonapi
6
+ module Controller
7
+ extend ActiveSupport::Concern
8
+ include Formatter
9
+ include JSONErrors
10
+
11
+ def self.include(base)
12
+ base.include Pundit
13
+
14
+ base.extend ClassMethods
15
+ end
16
+
17
+ def index
18
+ authorize model
19
+
20
+ render_json_api serializer.new(_resources, serializer_options).serializable_hash
21
+ end
22
+
23
+ def show
24
+ authorize _resource
25
+
26
+ render_not_found && return if _resource.kind_of? NilClass
27
+
28
+ render_json_api serializer.new(_resource).serializable_hash
29
+ end
30
+
31
+ def update
32
+ authorize model
33
+
34
+ render_not_found && return if _resource.kind_of? NilClass
35
+
36
+ if _resource.update_attributes _resource_params
37
+ render_json_api serializer.new(_resource).serializable_hash, status: :reset_content
38
+ else
39
+ render_unprocessable_entity
40
+ end
41
+ end
42
+
43
+ def destroy
44
+ authorize _resource
45
+
46
+ _resource.destroy
47
+ render_json_api serializer.new(_resource).serializable_hash, status: :no_content
48
+ end
49
+
50
+ module ClassMethods
51
+ def new(*args, &block)
52
+ instance = super
53
+ instance.instance_variable_set :@model, @model if @model
54
+ instance.instance_variable_set :@serializer, @serializer if @serializer
55
+ instance
56
+ end
57
+
58
+ def model_set(model)
59
+ @model = model
60
+ end
61
+
62
+ def serializer_set(serializer)
63
+ @serializer = serializer
64
+ end
65
+ end
66
+
67
+ private
68
+
69
+ def page
70
+ @page ||= params[:page] || 1
71
+ end
72
+
73
+ def limit
74
+ @limit ||= params[:limit] || 10
75
+ end
76
+
77
+ def meta
78
+ @meta ||= params[:meta].eql?("true")
79
+ end
80
+
81
+ def filter
82
+ @filter ||= params[:filter] || {}
83
+ end
84
+
85
+ def model
86
+ @model ||= controller_name.classify.constantize
87
+ end
88
+
89
+ def serializer
90
+ @serializer ||= "#{model.name}Serializer".constantize
91
+ end
92
+
93
+ def set_resource=(val)
94
+ @_resource = val
95
+ end
96
+
97
+ def _resource
98
+ @_resource ||= policy_scope(model).find_by_id(params[:id])
99
+ end
100
+
101
+ def _resources
102
+ @_resources ||= apply_filter(policy_scope(model))
103
+ .page(page)
104
+ .per(limit)
105
+ end
106
+
107
+ def resource_params
108
+ params.require(:data)
109
+ end
110
+
111
+ def serializer_options
112
+ {
113
+ params: {meta: meta},
114
+ links: serializer_links,
115
+ meta: serializer_meta,
116
+ include: serializer_include
117
+ }
118
+ end
119
+
120
+ def serializer_include
121
+ @serializer_include ||= []
122
+ end
123
+
124
+ def serializer_meta
125
+ @serializer_meta ||= {
126
+ pages: { total: _resources.total_pages, current: _resources.current_page },
127
+ results: { total: _resources.total_count, current: _resources.size }
128
+ }
129
+ end
130
+
131
+ def serializer_links
132
+ @serializer_links ||= {
133
+ nav: {
134
+ self: get_link_for(:self),
135
+ first: get_link_for(:first),
136
+ last: get_link_for(:last),
137
+ prev: get_link_for(:prev),
138
+ next: get_link_for(:next)
139
+ }
140
+ }
141
+ end
142
+
143
+ def get_link_for(keyword)
144
+ case keyword
145
+ when :self
146
+ index_url(page: page, limit: limit)
147
+ when :first
148
+ index_url(page: 1, limit: limit)
149
+ when :last
150
+ index_url(page: _resources.total_pages, limit: limit)
151
+ when :prev
152
+ index_url(page: _resources.prev_page, limit: limit) unless _resources.first_page?
153
+ when :next
154
+ index_url(page: _resources.next_page, limit: limit) unless _resources.last_page?
155
+ end
156
+ end
157
+ # rubocop:enable Metrics/MethodLength, Metrics/CyclomaticComplexity, Metrics/AbcSize
158
+
159
+ def index_url(options)
160
+ unless ENV['HOST']
161
+ raise "Environment variable 'HOST' not defined"
162
+ end
163
+
164
+ url_for controller: controller_name,
165
+ action: :index,
166
+ host: ENV['HOST'],
167
+ **options
168
+ end
169
+
170
+ def allowed_filters
171
+ model.column_names
172
+ end
173
+
174
+ def valid_filters
175
+ filter.select { |_filter| allowed_filters.include? _filter }
176
+ end
177
+
178
+ def valid_values_from_filter(field)
179
+ filter[field].split(',').reject(&:blank?).map {|val| "%#{val}%" }
180
+ end
181
+
182
+ def apply_filter(scope)
183
+ valid_filters.each_pair do |field, values|
184
+ scope = scope.where("#{field}::text ILIKE ANY ( array[?] )", valid_values_from_filter(field))
185
+ end
186
+ scope
187
+ end
188
+ end
189
+ end
@@ -0,0 +1,18 @@
1
+ module ActAsJsonapi
2
+ module Formatter
3
+ extend ActiveSupport::Concern
4
+
5
+ # Render json response and set content type to 'application/vnd.api+json'
6
+ def render_json_api(serializable_hash, options = {})
7
+ options.merge!(json_api_content_type)
8
+ args = { json: serializable_hash }.merge(options)
9
+ render args
10
+ end
11
+
12
+ private
13
+
14
+ def json_api_content_type
15
+ { content_type: 'application/vnd.api+json' }
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,65 @@
1
+ require_relative 'status_code_response'
2
+ require_relative 'request_error_serializer'
3
+
4
+ module ActAsJsonapi
5
+ module JSONErrors
6
+ extend ActiveSupport::Concern
7
+
8
+ def serializable(error_status, detail, detail_meta)
9
+ StatusCodeResponse.serializable(error_status, detail, detail_meta)
10
+ end
11
+
12
+ def translate_detail_code(detail_code)
13
+ detail = I18n.t("error_messages.#{detail_code.to_s}")
14
+ return detail unless detail.include?("translation missing")
15
+ detail = I18n.t("error_messages.err_standard")
16
+ end
17
+
18
+ def render_error(error_status, detail_code = nil, detail_meta = nil )
19
+ detail = translate_detail_code(detail_code)
20
+ serializer = ::RequestErrorSerializer.new serializable(error_status, detail , detail_meta)
21
+ render_json_api serializer, status: error_status
22
+ end
23
+
24
+ def render_not_found
25
+ render_error :not_found
26
+ end
27
+
28
+ def render_bad_request
29
+ render_error :bad_request
30
+ end
31
+
32
+ def render_not_authorized
33
+ render_error :unauthorized
34
+ end
35
+
36
+ def render_forbidden(ex)
37
+ render_error :forbidden, :err_forbidden, ex.message
38
+ end
39
+
40
+ def render_failed_dependency
41
+ render_error :failed_dependency
42
+ end
43
+
44
+ def render_unprocessable_entity
45
+ render_error :unprocessable_entity
46
+ end
47
+
48
+ def render_service_unavailable
49
+ render_error :service_unavailable
50
+ end
51
+
52
+ def render_conflict_request
53
+ render_error :conflict
54
+ end
55
+
56
+ private
57
+
58
+ # Render json response and set content type to 'application/vnd.api+json'
59
+ def render_json_api(serializable_hash, options = {})
60
+ options[:content_type] = 'application/vnd.api+json'
61
+ args = { json: serializable_hash }.merge(options)
62
+ render args
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,36 @@
1
+ require 'jsonapi/serializer'
2
+
3
+ module JSONAPI
4
+ # This module allows serialization of custom error objects to remain compliant
5
+ # with JSON:API specification
6
+ module ErrorSerializer
7
+ extend ActiveSupport::Concern
8
+
9
+ included do
10
+ attr_accessor :with_root_key
11
+
12
+ include JSONAPI::Serializer
13
+
14
+ def initialize(resource, options = {})
15
+ if resource.is_a? StandardError
16
+ resource
17
+ else
18
+ resource = Array.wrap(resource)
19
+ resource.collect! { |res| OpenStruct.new(res) }
20
+ end
21
+ super
22
+ @with_root_key = options[:with_root_key] != false
23
+ end
24
+
25
+ def hash_for_one_record
26
+ serialized_hash = [super[:data].dig(:attributes)]
27
+ !with_root_key ? serialized_hash : { errors: serialized_hash }
28
+ end
29
+
30
+ def hash_for_collection
31
+ serialized_hash = super[:data]&.map { |err| err[:attributes] }
32
+ !with_root_key ? serialized_hash : { errors: serialized_hash }
33
+ end
34
+ end
35
+ end
36
+ end
File without changes
@@ -0,0 +1,39 @@
1
+ require_relative 'jsonapi_error_serializer'
2
+
3
+ # Request Error Serializer
4
+ # Provides additional information about problems encountered while performing
5
+ # a request operation. The possible attributes are:
6
+ # +id+ a unique identifier for this particular occurrence of the problem.
7
+ # +title+ a short, human-readable summary of the problem
8
+ # +detail+ a human-readable explanation specific to this occurrence of the problem
9
+ # +code+ an application-specific error code, expressed as a string value.
10
+ # +status+ the HTTP status code applicable to this problem, expressed as a string value.
11
+ class RequestErrorSerializer
12
+ include JSONAPI::ErrorSerializer
13
+
14
+ attributes :id,
15
+ :title,
16
+ :detail,
17
+ :code,
18
+ :status,
19
+ :meta
20
+
21
+ # This is a generic active model error serializer that transform an
22
+ # ActiveModel::Errors object to a JSON:API compliant error serializer
23
+ # @params [ActiveModel::Errors] ActiveModel::Errors object
24
+ def self.from_active_model_errors(errors)
25
+ error_array = errors.full_messages.map do |error_msg|
26
+ {
27
+ id: SecureRandom.uuid,
28
+ title: error_msg,
29
+ detail: error_msg,
30
+ code: 'CLIENT400',
31
+ status: '400',
32
+ meta: {error: error_msg}
33
+ }
34
+ end
35
+
36
+ new(error_array)
37
+ end
38
+ end
39
+
@@ -0,0 +1,41 @@
1
+ module ActAsJsonapi
2
+ module StatusCodeResponse
3
+ SYMBOL_TO_STATUS_CODE = Rack::Utils::SYMBOL_TO_STATUS_CODE
4
+ STATUS_CODE_TO_SYMBOL = SYMBOL_TO_STATUS_CODE.invert
5
+
6
+ def self.serializable(error_status, detail, detail_meta)
7
+ if error_status.kind_of? Integer
8
+ serializable_from_int(error_status, detail, detail_meta)
9
+ else
10
+ serializable_from_sym(error_status, detail, detail_meta)
11
+ end
12
+ end
13
+
14
+ def self.serializable_from_int(code, detail, detail_meta)
15
+ code_i = code.to_i
16
+ error_sym = STATUS_CODE_TO_SYMBOL[code_i]
17
+
18
+ return {} unless error_sym
19
+
20
+ serializable error_sym, detail, detail_meta
21
+ end
22
+
23
+ def self.serializable_from_sym(error_sym, detail, detail_meta)
24
+ status_code = SYMBOL_TO_STATUS_CODE[error_sym]
25
+
26
+ return {} unless status_code
27
+ error_name = error_sym.to_s
28
+
29
+ {
30
+ id: SecureRandom.uuid,
31
+ title: error_name.gsub(/_/, ' '),
32
+ detail: detail,
33
+ code: status_code.to_s,
34
+ status: status_code.to_s,
35
+ meta: {
36
+ error: detail_meta
37
+ }
38
+ }
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActAsJsonapi
4
+ VERSION = "0.1.2"
5
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActAsJsonapi
4
+ require_relative "act_as_jsonapi/version"
5
+ require_relative "act_as_jsonapi/controller"
6
+ require_relative "act_as_jsonapi/formatter"
7
+ require_relative "act_as_jsonapi/json_errors"
8
+
9
+ class Error < StandardError; end
10
+ end
metadata ADDED
@@ -0,0 +1,157 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: act_as_jsonapi
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.2
5
+ platform: ruby
6
+ authors:
7
+ - leizzer
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-03-13 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rubocop
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.7'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.7'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rspec
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '3.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '3.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '13.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '13.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: jsonapi-serializer
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: 2.2.0
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: 2.2.0
69
+ - !ruby/object:Gem::Dependency
70
+ name: activesupport
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '7.0'
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '7.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: pundit
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '2.1'
90
+ type: :runtime
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '2.1'
97
+ description: Act as JSONAPI is a small and flexible gem on top of `jsonapi_serializer`. By
98
+ including Act as JSONAPI in your controllers you instantly get all basic controller
99
+ actions for the model. You can override the model and serializer if the name of
100
+ the controller doesn't match the model. The json formatter and errors can be used
101
+ separatly.
102
+ email:
103
+ executables: []
104
+ extensions: []
105
+ extra_rdoc_files: []
106
+ files:
107
+ - ".github/workflows/main.yml"
108
+ - ".gitignore"
109
+ - ".rspec"
110
+ - ".rubocop.yml"
111
+ - CHANGELOG.md
112
+ - CODE_OF_CONDUCT.md
113
+ - Gemfile
114
+ - LICENSE.txt
115
+ - README.md
116
+ - Rakefile
117
+ - act_as_jsonapi.gemspec
118
+ - bin/console
119
+ - bin/setup
120
+ - lib/act_as_jsonapi.rb
121
+ - lib/act_as_jsonapi/controller.rb
122
+ - lib/act_as_jsonapi/formatter.rb
123
+ - lib/act_as_jsonapi/json_errors.rb
124
+ - lib/act_as_jsonapi/jsonapi_error_serializer.rb
125
+ - lib/act_as_jsonapi/null_object.rb
126
+ - lib/act_as_jsonapi/request_error_serializer.rb
127
+ - lib/act_as_jsonapi/status_code_response.rb
128
+ - lib/act_as_jsonapi/version.rb
129
+ homepage: https://github.com/leizzer/act_as_jsonapi
130
+ licenses:
131
+ - MIT
132
+ metadata:
133
+ allowed_push_host: https://rubygems.org
134
+ homepage_uri: https://github.com/leizzer/act_as_jsonapi
135
+ source_code_uri: https://github.com/leizzer/act_as_jsonapi
136
+ changelog_uri: https://github.com/leizzer/act_as_jsonapi/blob/main/CHANGELOG.md
137
+ post_install_message:
138
+ rdoc_options: []
139
+ require_paths:
140
+ - lib
141
+ required_ruby_version: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - ">="
144
+ - !ruby/object:Gem::Version
145
+ version: 2.4.0
146
+ required_rubygems_version: !ruby/object:Gem::Requirement
147
+ requirements:
148
+ - - ">="
149
+ - !ruby/object:Gem::Version
150
+ version: '0'
151
+ requirements: []
152
+ rubygems_version: 3.2.15
153
+ signing_key:
154
+ specification_version: 4
155
+ summary: Light weight gem on top of `jsonapi_serializer` and `pundit` to keep controllers
156
+ DRY
157
+ test_files: []