dry_struct_parser 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c5811b88b3ac827144eca5576cf9542a9b379620a2640fcefee9101b270160fb
4
+ data.tar.gz: 8a7a8c13f315867df7081600d661b944b0f81f34aba08dba120273eafdc5dcd0
5
+ SHA512:
6
+ metadata.gz: e1f9cdf5d1fd86d97cde45af23482b5c35e78b3b12a7d0ef6600345068ffcb5b78e428fa93bc672f2d209665aa3322bbc199d69b312be37d0c4869034140631b
7
+ data.tar.gz: 1a90d6518ef72ed016e66438ef2fbd910a3d99c984e563374e676040327a57c86a8c563538b163a861adcf2fb9becaffb99c550abe02b17fde0be8394c2e175a
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,36 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+ Exclude:
4
+ - 'spec/**/*.rb'
5
+
6
+ Style/StringLiterals:
7
+ Enabled: true
8
+ EnforcedStyle: double_quotes
9
+
10
+ Style/StringLiteralsInInterpolation:
11
+ Enabled: true
12
+ EnforcedStyle: double_quotes
13
+
14
+ Layout/LineLength:
15
+ Max: 120
16
+
17
+ Metrics/MethodLength:
18
+ Max: 20
19
+
20
+ Documentation:
21
+ Enabled: false
22
+
23
+ Metrics/AbcSize:
24
+ Enabled: false
25
+
26
+ Metrics/BlockLength:
27
+ Max: 40
28
+
29
+ Metrics/ClassLength:
30
+ Max: 200
31
+
32
+ Metrics/PerceivedComplexity:
33
+ Max: 10
34
+
35
+ Metrics/CyclomaticComplexity:
36
+ Max: 10
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-01-12
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 janeterziev@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/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Jane-Terziev
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,126 @@
1
+ # DryStructParser
2
+
3
+ Generate a readable hash from a dry-struct for easier manipulation
4
+
5
+ The gem is still work in progress and is not yet fully tested.
6
+ ## Installation
7
+
8
+ Add this line to your application's Gemfile:
9
+
10
+ ```ruby
11
+ gem 'dry_struct_parser'
12
+ ```
13
+
14
+ And then execute:
15
+
16
+ bundle install
17
+
18
+ ## Usage
19
+
20
+ #### Parsing a Dry::Struct
21
+ Lets say we have the following Dry::Validation::Contract definition:
22
+
23
+ class DTO1 < Dry::Struct
24
+ attribute :dto1_field, Types::String
25
+ end
26
+
27
+ class DTO2 < Dry::Struct
28
+ attribute :dto2_field, Types::String
29
+ end
30
+
31
+ class DTO < Dry::Struct
32
+ attribute :dynamic_dto, DTO1 | DTO2
33
+ end
34
+ parser = DryStructParser::StructSchemaParser.new
35
+
36
+ parser.call(DTO)
37
+ => {
38
+ "dynamic_dto": [ # ARRAY
39
+ {
40
+ "type": "hash",
41
+ "required": true,
42
+ "nullable": false,
43
+ "keys": {
44
+ "dto1_field": {
45
+ "type": "string",
46
+ "required": true,
47
+ "nullable": false
48
+ }
49
+ }
50
+ },
51
+ {
52
+ "type": "hash",
53
+ "required": true,
54
+ "nullable": false,
55
+ "keys": {
56
+ "dto2_field": {
57
+ "type": "string",
58
+ "required": true,
59
+ "nullable": false
60
+ }
61
+ }
62
+ }
63
+ ]
64
+ }
65
+
66
+ The required key depends on whether we define the field as attribute or attribute?
67
+
68
+ For more complex types, for example DTO1 | DTO2 or Types::Array.of(DTO1 | DTO2),
69
+ the parser converts the field value to an array of both schemas.
70
+
71
+ ## Overriding fields
72
+ You can also modify the fields by passing a block after the .call() method.
73
+
74
+ DryStructParser::StructSchemaParser.new.call(DTO) do |it|
75
+ # types = string/integer/hash/array
76
+
77
+ # Remove a field
78
+ its.keys = it.keys.except(:field_name)
79
+
80
+ # Add new field on root level
81
+ it.keys[:new_field_name] = { type: type, required: true/false, nullable: true/false }
82
+
83
+ # Add a new field in nested hash/array
84
+ it.keys[:nested_field][:keys][:new_field_name] = {
85
+ type: type, required: true/false, nullable: true/false
86
+ }
87
+
88
+ # Remove a field in nested hash/array
89
+ it.keys = it.keys[:nested_field][:keys].except(:field_name)
90
+
91
+ # Add an array or hash
92
+ it.keys[:nested_field] = {
93
+ type: "array/hash", required: true/false, nullable: true/false, keys: {
94
+ # List all nested fields
95
+ new_field: { type: :type, required: true/false, nullable: true/false }
96
+ }
97
+ }
98
+
99
+ # Add an Array of primitive types, type field needs to be the element type(string, integer, float),
100
+ and add an array: true flag
101
+
102
+ it.keys[:array_field_name] = {
103
+ type: type, array: true, required: true/false, nullable: true/false
104
+ }
105
+
106
+ end
107
+
108
+
109
+ ## Development
110
+
111
+ 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.
112
+
113
+ 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 tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
114
+
115
+ ## Contributing
116
+
117
+ Bug reports and pull requests are welcome on GitHub at https://github.com/Jane-Terziev/dry_struct_parser. 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]/dry_struct_parser/blob/master/CODE_OF_CONDUCT.md).
118
+
119
+
120
+ ## License
121
+
122
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
123
+
124
+ ## Code of Conduct
125
+
126
+ Everyone interacting in the DryStructParser project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/dry_struct_parser/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,129 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DryStructParser
4
+ class StructSchemaParser
5
+ PREDICATE_TYPES = {
6
+ String: "string",
7
+ Integer: "integer",
8
+ TrueClass: "boolean",
9
+ FalseClass: "boolean",
10
+ Float: "float",
11
+ Date: "date",
12
+ DateTime: "datetime",
13
+ Time: "time"
14
+ }.freeze
15
+
16
+ attr_reader :keys
17
+
18
+ def initialize
19
+ @keys = {}
20
+ end
21
+
22
+ def to_h
23
+ { keys: keys }
24
+ end
25
+
26
+ def call(struct, &block)
27
+ @keys = {}
28
+ visit(struct.schema.to_ast)
29
+ instance_eval(&block) if block_given?
30
+ self
31
+ end
32
+
33
+ def visit(node, opts = {})
34
+ meth, rest = node
35
+ public_send(:"visit_#{meth}", rest, opts)
36
+ end
37
+
38
+ def visit_constructor(node, opts = {})
39
+ visit(node[0], opts)
40
+ end
41
+
42
+ def visit_schema(node, opts = {})
43
+ target = (key = opts[:key]) ? self.class.new : self
44
+ required = opts.fetch(:required, true)
45
+ nullable = opts.fetch(:nullable, false)
46
+ node[0].each { |child| target.visit(child) }
47
+ return unless key
48
+
49
+ target_info = target.to_h if opts[:member]
50
+ type = opts[:array] ? "array" : "hash"
51
+ definition = {
52
+ type: type,
53
+ required: required,
54
+ nullable: nullable,
55
+ **target_info
56
+ }
57
+ if opts[:oneOf]
58
+ keys[key] ? keys[key] << definition : keys[key] = [definition]
59
+ else
60
+ keys[key] = definition
61
+ end
62
+
63
+ keys[key]
64
+ end
65
+
66
+ def visit_key(node, opts = {})
67
+ name, required, rest = node
68
+ opts[:key] = name
69
+ opts[:required] = required
70
+ visit(rest, opts)
71
+ end
72
+
73
+ def visit_constrained(node, opts = {})
74
+ node.each { |it| visit(it, opts) }
75
+ end
76
+
77
+ def visit_nominal(_node, _opts); end
78
+
79
+ def visit_predicate(node, opts = {})
80
+ name, rest = node
81
+ type = rest[0][1]
82
+ if name.equal?(:type?)
83
+ type = type.to_s.to_sym
84
+ return unless PREDICATE_TYPES[type]
85
+
86
+ type_definition = {
87
+ type: PREDICATE_TYPES[type],
88
+ required: opts.fetch(:required),
89
+ nullable: opts.fetch(:nullable, false)
90
+ }
91
+ type_definition[:array] = opts[:array] if opts[:array]
92
+ keys[opts[:key]] = type_definition
93
+ elsif name.equal?(:included_in?)
94
+ type += [nil] if opts.fetch(:nullable, false)
95
+ keys[opts[:key]][:enum] = type
96
+ end
97
+ end
98
+
99
+ def visit_and(node, opts = {})
100
+ left, right = node
101
+ visit(left, opts)
102
+ visit(right, opts)
103
+ end
104
+
105
+ def visit_enum(node, opts = {})
106
+ visit(node[0], opts)
107
+ end
108
+
109
+ def visit_sum(node, opts = {})
110
+ if node[0][0].equal?(:constrained)
111
+ opts[:nullable] = true if node[0][1][0][1][0].equal?(NilClass)
112
+ visit(node[1], opts) # ignore NilClass constrained
113
+ elsif node[0][0].equal?(:struct) || node[0][0].equal?(:sum)
114
+ opts[:oneOf] = true
115
+ node.each { |child| visit(child, opts) unless child.is_a?(Hash) }
116
+ end
117
+ end
118
+
119
+ def visit_struct(node, opts = {})
120
+ opts[:member] = true
121
+ visit(node[1], opts)
122
+ end
123
+
124
+ def visit_array(node, opts = {})
125
+ opts[:array] = true
126
+ visit(node[0], opts)
127
+ end
128
+ end
129
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry/types"
4
+
5
+ module DryStructParser
6
+ module Types
7
+ include ::Dry.Types()
8
+ end
9
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DryStructParser
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "dry_struct_parser/version"
4
+ require_relative "dry_struct_parser/struct_schema_parser"
5
+
6
+ module DryStructParser
7
+ class Error < StandardError; end
8
+ # Your code goes here...
9
+ end
@@ -0,0 +1,4 @@
1
+ module DryStructParser
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,74 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: dry_struct_parser
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Jane-Terziev
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-01-12 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: dry-struct
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1'
27
+ description: |-
28
+ A parser which converts dry-struct schema into a readable hash for further
29
+ manipulation
30
+ email:
31
+ - janeterziev@gmail.com
32
+ executables: []
33
+ extensions: []
34
+ extra_rdoc_files: []
35
+ files:
36
+ - ".rspec"
37
+ - ".rubocop.yml"
38
+ - CHANGELOG.md
39
+ - CODE_OF_CONDUCT.md
40
+ - LICENSE.txt
41
+ - README.md
42
+ - Rakefile
43
+ - lib/dry_struct_parser.rb
44
+ - lib/dry_struct_parser/struct_schema_parser.rb
45
+ - lib/dry_struct_parser/types.rb
46
+ - lib/dry_struct_parser/version.rb
47
+ - sig/dry_struct_parser.rbs
48
+ homepage: https://github.com/Jane-Terziev/dry_struct_parser
49
+ licenses:
50
+ - MIT
51
+ metadata:
52
+ allowed_push_host: https://rubygems.org
53
+ homepage_uri: https://github.com/Jane-Terziev/dry_struct_parser
54
+ source_code_uri: https://github.com/Jane-Terziev/dry_struct_parser
55
+ post_install_message:
56
+ rdoc_options: []
57
+ require_paths:
58
+ - lib
59
+ required_ruby_version: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - ">="
62
+ - !ruby/object:Gem::Version
63
+ version: 2.6.0
64
+ required_rubygems_version: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ requirements: []
70
+ rubygems_version: 3.4.10
71
+ signing_key:
72
+ specification_version: 4
73
+ summary: Generate a readable hash from a dry-struct schema
74
+ test_files: []