strum-json 0.0.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: 0ec9df9ce86346705778fc22f69368c79376ea28ffd767c956e1868e01adda6e
4
+ data.tar.gz: 51f495a740b72b403301008d7d0939d6e86646e21c91c4318d501880d8c7d5a8
5
+ SHA512:
6
+ metadata.gz: 3e35a9c659744ee218fb3822f9ffa36e7007e54b6f9b79b41e200885746f999e43bf72685313644066a4eb10dce261db32393dc4738470772a8bc9c853cd135a
7
+ data.tar.gz: 645e4824beeebec8d4ff4c1f8c884f5acfed433c450e4d3c2c652e354252c2ae0ede680fdbddfc9f98179d837ed8c0889f8d18e74142752b39d4f94cd818d10b
data/.gitignore ADDED
@@ -0,0 +1,23 @@
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
12
+
13
+ # Editor directories and files
14
+ .idea
15
+ .vscode
16
+ *.suo
17
+ *.ntvs*
18
+ *.njsproj
19
+ *.sln
20
+ *.sw*
21
+
22
+ # builds
23
+ *.gem
data/.gitlab-ci.yml ADDED
@@ -0,0 +1,3 @@
1
+ include:
2
+ - project: 'strum-rb/ci-cd'
3
+ file: '/strum-rb/.gitlab-ci.yml'
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,26 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+ NewCops: enable
4
+
5
+ # Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }.
6
+ Style/HashSyntax:
7
+ Enabled: true
8
+
9
+ # Method definitions after `private` or `protected` isolated calls need one
10
+ # extra level of indentation.
11
+ Layout/IndentationConsistency:
12
+ Enabled: true
13
+ EnforcedStyle: indented_internal_methods
14
+
15
+ # Two spaces, no tabs (for indentation).
16
+ Layout/IndentationWidth:
17
+ Enabled: true
18
+
19
+ # Check quotes usage according to lint rule below.
20
+ Style/StringLiterals:
21
+ Enabled: true
22
+ EnforcedStyle: double_quotes
23
+
24
+ Metrics/LineLength:
25
+ Max: 120
26
+ IgnoredPatterns: ['\A#']
@@ -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 sn@nazarov.com.ua. 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,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in strum-json.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 1.7"
13
+ gem "rubocop-rake", "~> 0.5"
14
+ gem "rubocop-rspec", "~> 2.2"
data/Gemfile.lock ADDED
@@ -0,0 +1,74 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ strum-json (0.0.2)
5
+ dry-inflector (~> 0.2.0)
6
+ json (~> 2.3)
7
+ json-schema (~> 2.8.1)
8
+ strum-service (~> 0.1.0)
9
+
10
+ GEM
11
+ remote: https://rubygems.org/
12
+ specs:
13
+ addressable (2.7.0)
14
+ public_suffix (>= 2.0.2, < 5.0)
15
+ ast (2.4.2)
16
+ diff-lcs (1.4.4)
17
+ dry-inflector (0.2.0)
18
+ json (2.5.1)
19
+ json-schema (2.8.1)
20
+ addressable (>= 2.4)
21
+ parallel (1.20.1)
22
+ parser (3.0.1.1)
23
+ ast (~> 2.4.1)
24
+ public_suffix (4.0.6)
25
+ rainbow (3.0.0)
26
+ rake (13.0.3)
27
+ regexp_parser (2.1.1)
28
+ rexml (3.2.5)
29
+ rspec (3.10.0)
30
+ rspec-core (~> 3.10.0)
31
+ rspec-expectations (~> 3.10.0)
32
+ rspec-mocks (~> 3.10.0)
33
+ rspec-core (3.10.1)
34
+ rspec-support (~> 3.10.0)
35
+ rspec-expectations (3.10.1)
36
+ diff-lcs (>= 1.2.0, < 2.0)
37
+ rspec-support (~> 3.10.0)
38
+ rspec-mocks (3.10.2)
39
+ diff-lcs (>= 1.2.0, < 2.0)
40
+ rspec-support (~> 3.10.0)
41
+ rspec-support (3.10.2)
42
+ rubocop (1.14.0)
43
+ parallel (~> 1.10)
44
+ parser (>= 3.0.0.0)
45
+ rainbow (>= 2.2.2, < 4.0)
46
+ regexp_parser (>= 1.8, < 3.0)
47
+ rexml
48
+ rubocop-ast (>= 1.5.0, < 2.0)
49
+ ruby-progressbar (~> 1.7)
50
+ unicode-display_width (>= 1.4.0, < 3.0)
51
+ rubocop-ast (1.5.0)
52
+ parser (>= 3.0.1.1)
53
+ rubocop-rake (0.5.1)
54
+ rubocop
55
+ rubocop-rspec (2.3.0)
56
+ rubocop (~> 1.0)
57
+ rubocop-ast (>= 1.1.0)
58
+ ruby-progressbar (1.11.0)
59
+ strum-service (0.1.0)
60
+ unicode-display_width (2.0.0)
61
+
62
+ PLATFORMS
63
+ x86_64-linux
64
+
65
+ DEPENDENCIES
66
+ rake (~> 13.0)
67
+ rspec (~> 3.0)
68
+ rubocop (~> 1.7)
69
+ rubocop-rake (~> 0.5)
70
+ rubocop-rspec (~> 2.2)
71
+ strum-json!
72
+
73
+ BUNDLED WITH
74
+ 2.2.15
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Serhiy Nazarov
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,43 @@
1
+ # Strum::Json
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/strum/json`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'strum-json'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install strum-json
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ 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.
30
+
31
+ 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).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/strum-json. 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]/strum-json/blob/master/CODE_OF_CONDUCT.md).
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the Strum::Json project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/strum-json/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "strum/json"
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
data/lib/strum/json.rb ADDED
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "json/version"
4
+ require_relative "json/serializer"
5
+ require_relative "json/deserializer"
6
+ require_relative "json/schema"
7
+
8
+ module Strum
9
+ module Json
10
+ class Error < StandardError; end
11
+ # Your code goes here...
12
+ end
13
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "strum/service"
4
+ require "dry-inflector"
5
+
6
+ module Strum
7
+ module Json
8
+ class DeepKeysToSym
9
+ include Strum::Service
10
+
11
+ def call
12
+ output(deep_transform_keys(input))
13
+ end
14
+
15
+ def audit
16
+ required
17
+ end
18
+
19
+ private
20
+
21
+ def deep_transform_keys(hash)
22
+ return hash unless hash.is_a?(Hash)
23
+
24
+ hash.each_with_object({}) do |(key, value), result|
25
+ result[inflector.underscore(key).to_sym] = deep_transform_keys(value)
26
+ end
27
+ end
28
+
29
+ def inflector
30
+ @inflector ||= Dry::Inflector.new
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,133 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry-inflector"
4
+ require "strum/service"
5
+
6
+ module Strum
7
+ module Json
8
+ # Deserialize JSON-API to hash(s)
9
+ class Deserializer
10
+ include Strum::Service
11
+
12
+ def call
13
+ output(root_data[:data] ? prepare_output : root_errors[:errors])
14
+ end
15
+
16
+ def audit
17
+ add_error(:root, :data_and_errors_must_not_coexist) unless !root_data[:data] ^ !root_errors[:errors]
18
+ end
19
+
20
+ def root_data
21
+ @root_data ||= deep_transform_keys(input)
22
+ end
23
+
24
+ def root_errors
25
+ @root_errors ||= deep_transform_keys(input)
26
+ end
27
+
28
+ def deep_transform_keys(object)
29
+ keys_to_sym = lambda do |object|
30
+ case object
31
+ when Hash
32
+ object.each_key do |key|
33
+ value = object.delete(key)
34
+ object[(key.respond_to?(:to_sym) ? inflector.underscore(key).to_sym : key)] = keys_to_sym[value]
35
+ end
36
+ object
37
+ when Array
38
+ object.map! { |e| keys_to_sym[e] }
39
+ else
40
+ object
41
+ end
42
+ end
43
+ merge_relationships = lambda do |object|
44
+ handle_attributes(object)
45
+ end
46
+ result = keys_to_sym >> merge_relationships
47
+ result[object]
48
+ end
49
+
50
+ def merge_relations(hash)
51
+ if hash[:data].is_a?(Array)
52
+ parse_array_relationships(hash)
53
+ else
54
+ relationships = relations(hash)
55
+ included = includes(hash)
56
+ prepare_relationships = lambda { |hash|
57
+ hash.each do |key, value|
58
+ if value.is_a?(Hash)
59
+ hash[key.to_sym] = (value.values_at(:attributes)&.first || value.values_at(:data)&.first || value)
60
+ end
61
+ end
62
+ }
63
+ if relationships && hash[:data][:attributes]
64
+ hash[:data][:attributes].merge!(prepare_relationships[relationships])
65
+ end
66
+ hash[:data][:attributes].merge!(prepare_includes(included)) if included && hash[:data][:attributes]
67
+ end
68
+ hash
69
+ end
70
+
71
+ def parse_array_relationships(hash)
72
+ prepare_nested = lambda { |hash|
73
+ hash.each do |key, value|
74
+ hash[key.to_sym] = value.values_at(:data)&.first if value.is_a?(Hash)
75
+ end
76
+ }
77
+ hash[:data].each do |element|
78
+ relationships, included = element.values_at(:relationships, :included)
79
+ element[:attributes].merge!(prepare_nested[relationships]) if relationships
80
+ element[:attributes].merge!(prepare_nested[included]) if included
81
+ end
82
+ end
83
+
84
+ def relations(hash)
85
+ case hash[:data]
86
+ when Array
87
+ hash[:data].map { |i| i[:relationships] }
88
+ when Hash
89
+ hash[:data][:relationships]
90
+ else
91
+ hash[:data]
92
+ end
93
+ end
94
+
95
+ def includes(hash)
96
+ hash[:included]
97
+ end
98
+
99
+ def prepare_includes(includes)
100
+ includes.each_with_object({}) do |h, e|
101
+ e[h[:type].to_sym] ||= []
102
+ e[h[:type].to_sym] << h[:attributes]
103
+ end
104
+ end
105
+
106
+ def handle_attributes(object)
107
+ case object
108
+ when Array
109
+ object.map { |i| merge_relations(i) }
110
+ when Hash
111
+ merge_relations(object)
112
+ else
113
+ object
114
+ end
115
+ end
116
+
117
+ def prepare_output
118
+ case root_data
119
+ when Array
120
+ root_data.map { |i| i[:data][:attributes] }
121
+ when Hash
122
+ root_data[:data].is_a?(Array) ? root_data[:data].map { |i| i[:attributes] } : root_data[:data][:attributes]
123
+ else
124
+ root_data
125
+ end
126
+ end
127
+
128
+ def inflector
129
+ @inflector = Dry::Inflector.new
130
+ end
131
+ end
132
+ end
133
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "strum/json/schema/validate"
4
+ require "strum/json/schema/cast"
5
+
6
+ module Strum
7
+ module Json
8
+ module Schema
9
+ class NoValue; end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "strum/service"
4
+
5
+ module Strum
6
+ module Json
7
+ module Schema
8
+ class Cast
9
+ include Strum::Service
10
+
11
+ def call
12
+ output(casted(input, args[:schema]))
13
+ end
14
+
15
+ def audit
16
+ add_error(:schema, :not_found) unless args[:schema].is_a?(Hash)
17
+ end
18
+
19
+ protected
20
+
21
+ def casted(input_data, schema, path = [])
22
+ item = custom_dig(input_data, path)
23
+
24
+ return item if item.is_a?(NoValue)
25
+
26
+ case schema[:type]
27
+ when Array
28
+ schema[:type].reduce(nil) do |type, x|
29
+ new_schema = schema.clone
30
+ new_schema[:type] = x
31
+ type || casted(input_data, new_schema, path)
32
+ end
33
+ when "object"
34
+ if item.is_a?(Hash) && schema[:properties].is_a?(Hash)
35
+ item.map do |key, val|
36
+ if (prop = schema[:properties][key])
37
+ [key,
38
+ casted(input_data, prop, path + [key])]
39
+ else
40
+ [key, val]
41
+ end
42
+ end.filter { |pair| !pair[1].is_a?(NoValue) }.to_h
43
+ end
44
+ when "array"
45
+ if item.is_a?(Array) && schema[:items].is_a?(Hash)
46
+ (0..(item.length - 1)).reduce([]) { |res, idx| res << casted(input_data, schema[:items], path + [idx]) }
47
+ end
48
+ when "string"
49
+ item.to_s
50
+ when "integer", "number"
51
+ case item
52
+ when Numeric
53
+ item
54
+ when String, Symbol
55
+ (item.to_s.to_f % 1).positive? ? item.to_s.to_f : item.to_s.to_i
56
+ end
57
+ when "boolean"
58
+ item.to_s.downcase == "true"
59
+ when "jsonb"
60
+ if Module.constants.include?(:Sequel) && Sequel.methods.include?(:pg_jsonb_wrap)
61
+ Sequel.pg_jsonb_wrap(item)
62
+ else
63
+ add_error(:schema, "jsonb type is not supported")
64
+ end
65
+ when nil, ""
66
+ item
67
+ else
68
+ add_error(:schema, :invalid_type)
69
+ end
70
+ end
71
+
72
+ def custom_dig(obj, path)
73
+ path.reduce(obj) { |item, x| item.fetch(x) { |_it| return NoValue.new } }
74
+ end
75
+ end
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "strum/service"
4
+ require "json-schema"
5
+
6
+ module Strum
7
+ module Json
8
+ module Schema
9
+ class Validate
10
+ include Strum::Service
11
+
12
+ def call
13
+ array_errors = JSON::Validator.fully_validate(args[:schema], input, errors_as_objects: true)
14
+ array_errors.each { |error| add_error(*parse_json_schema_error(error)) }
15
+ output(input)
16
+ end
17
+
18
+ def audit
19
+ add_error(:schema, :not_found) unless args[:schema].is_a?(Hash)
20
+ end
21
+
22
+ protected
23
+
24
+ def parse_json_schema_error(error)
25
+ id = error[:fragment].sub(/#/, "input")
26
+ keys = id.split("/")
27
+ last_key = keys.map { |key| key =~ /[0-9]+/ ? "[#{key}]" : ".#{key}" }.join[1..]
28
+ value = error[:message][0, error[:message].index(/ in schema/)].sub(error[:fragment], last_key)
29
+ [last_key.to_sym, value]
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "strum/json/serializer_class"
4
+ require "dry/inflector"
5
+
6
+ module Strum
7
+ module Json
8
+ module Serializer
9
+ def self.const_missing(name)
10
+ Class.new do
11
+ include Strum::Service
12
+ define_method :call do
13
+ require "serializers/#{Dry::Inflector.new.underscore(name)}_serializer"
14
+ serializer_class = Strum::Json::SerializerClass.call(name: name)
15
+ output(serializer_class.new(model, options).serializable_hash)
16
+ end
17
+
18
+ define_method :model do
19
+ return input if input.is_a?(Sequel::Model)
20
+ return input if input.is_a?(Dry::Struct)
21
+ return input if input.is_a?(Array) && (input.first.is_a?(Sequel::Model) || input.first.is_a?(Dry::Struct))
22
+
23
+ input[:model]
24
+ end
25
+
26
+ define_method :options do
27
+ return {} if input.is_a?(Sequel::Model)
28
+ return {} if input.is_a?(Dry::Struct)
29
+ return {} if input.is_a?(Array)
30
+
31
+ input.except(:model)
32
+ end
33
+ end
34
+ end
35
+
36
+ def self.call(model, **options)
37
+ const_get(model.class.name.split("::").last, false).call(options.merge(model: model))
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "strum/service"
4
+
5
+ module Strum
6
+ module Json
7
+ class SerializerClass
8
+ include Strum::Service
9
+
10
+ def call
11
+ output(Kernel.const_get("#{name}Serializer"))
12
+ rescue StandardError => e
13
+ add_error(:serializer, e)
14
+ end
15
+
16
+ def audit
17
+ required(:name)
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Strum
4
+ module Json
5
+ VERSION = "0.0.2"
6
+ end
7
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/strum/json/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "strum-json"
7
+ spec.version = Strum::Json::VERSION
8
+ spec.authors = ["Serhiy Nazarov"]
9
+ spec.email = ["sn@nazarov.com.ua"]
10
+
11
+ spec.summary = "Serialize and deserialize json"
12
+ spec.description = "Serialize and deserialize json"
13
+ spec.homepage = "https://gitlab.com/strum-rb/strum-json"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.6.0")
16
+
17
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
18
+
19
+ spec.metadata["homepage_uri"] = spec.homepage
20
+ spec.metadata["source_code_uri"] = "https://gitlab.com/strum-rb/strum-json"
21
+ spec.metadata["changelog_uri"] = "https://gitlab.com/strum-rb/strum-json/CHANGELOG.md"
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
26
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
27
+ end
28
+ spec.bindir = "exe"
29
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
30
+ spec.require_paths = ["lib"]
31
+
32
+ spec.add_dependency "dry-inflector", "~> 0.2.0"
33
+ spec.add_dependency "json", "~> 2.3"
34
+ spec.add_dependency "json-schema", "~> 2.8.1"
35
+ spec.add_dependency "strum-service", "~> 0.1.0"
36
+ end
metadata ADDED
@@ -0,0 +1,125 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: strum-json
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.2
5
+ platform: ruby
6
+ authors:
7
+ - Serhiy Nazarov
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-05-10 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: dry-inflector
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.2.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.2.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: json
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '2.3'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '2.3'
41
+ - !ruby/object:Gem::Dependency
42
+ name: json-schema
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: 2.8.1
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: 2.8.1
55
+ - !ruby/object:Gem::Dependency
56
+ name: strum-service
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: 0.1.0
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: 0.1.0
69
+ description: Serialize and deserialize json
70
+ email:
71
+ - sn@nazarov.com.ua
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - ".gitignore"
77
+ - ".gitlab-ci.yml"
78
+ - ".rspec"
79
+ - ".rubocop.yml"
80
+ - CODE_OF_CONDUCT.md
81
+ - Gemfile
82
+ - Gemfile.lock
83
+ - LICENSE.txt
84
+ - README.md
85
+ - Rakefile
86
+ - bin/console
87
+ - bin/setup
88
+ - lib/strum/json.rb
89
+ - lib/strum/json/deep_keys_to_sym.rb
90
+ - lib/strum/json/deserializer.rb
91
+ - lib/strum/json/schema.rb
92
+ - lib/strum/json/schema/cast.rb
93
+ - lib/strum/json/schema/validate.rb
94
+ - lib/strum/json/serializer.rb
95
+ - lib/strum/json/serializer_class.rb
96
+ - lib/strum/json/version.rb
97
+ - strum-json.gemspec
98
+ homepage: https://gitlab.com/strum-rb/strum-json
99
+ licenses:
100
+ - MIT
101
+ metadata:
102
+ allowed_push_host: https://rubygems.org
103
+ homepage_uri: https://gitlab.com/strum-rb/strum-json
104
+ source_code_uri: https://gitlab.com/strum-rb/strum-json
105
+ changelog_uri: https://gitlab.com/strum-rb/strum-json/CHANGELOG.md
106
+ post_install_message:
107
+ rdoc_options: []
108
+ require_paths:
109
+ - lib
110
+ required_ruby_version: !ruby/object:Gem::Requirement
111
+ requirements:
112
+ - - ">="
113
+ - !ruby/object:Gem::Version
114
+ version: 2.6.0
115
+ required_rubygems_version: !ruby/object:Gem::Requirement
116
+ requirements:
117
+ - - ">="
118
+ - !ruby/object:Gem::Version
119
+ version: '0'
120
+ requirements: []
121
+ rubygems_version: 3.1.6
122
+ signing_key:
123
+ specification_version: 4
124
+ summary: Serialize and deserialize json
125
+ test_files: []