donatello 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: 8fc1cb1e5179e6acc73f3d93625665ecfc3bb4e3097d1858723070ddf98045fd
4
+ data.tar.gz: b499b9e438011d5e5e80ebd8df6e0bde09037288e8aac5f923c7e7ee55accad3
5
+ SHA512:
6
+ metadata.gz: 91ad3fb4dc6c934d3fe463ee8e9853ce8fa7cb318ac4aff65ab97f6c4d782df44d66827cf40a2e610855dc2445c301bafe1e8639dc18e1e4d4bce6b1befabeb9
7
+ data.tar.gz: 1bb867434862d3bc2d9cf26c0d979f5d815cd891ec13ef50fbe70e56f3d4dc576dc10372a71ced5dfe5b369f750243c2ec26c601f372579d8e2fc65f9119bffa
data/.rubocop.yml ADDED
@@ -0,0 +1,8 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.0
3
+
4
+ Style/StringLiterals:
5
+ EnforcedStyle: double_quotes
6
+
7
+ Style/StringLiteralsInInterpolation:
8
+ EnforcedStyle: double_quotes
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-05-05
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 dave@devfarm.io. 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 Dave Rogers
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,151 @@
1
+ # Donatello
2
+
3
+ Donatello is a Ruby gem for effortlessly applying YAML-defined serialization schemas to Ruby objects, utilizing the speed of the Oj gem for optimal JSON output.
4
+
5
+ After spending a lot of time with GraphQL, when I started working with other types of JSON APIs, I missed being able to define my schema centrally.
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'donatello'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ ```bash
18
+ $ bundle install
19
+ ```
20
+
21
+ Or install it yourself with:
22
+
23
+ ```bash
24
+ $ gem install donatello
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ ### Defining a Schema
30
+
31
+ Create a YAML file in your Rails project (e.g., config/serialization_schema.yml) that defines your serialization schema:
32
+
33
+ ```yaml
34
+ # Mixed-in field set serializers (similar concept to fragments in GraphQL)
35
+ common_fields:
36
+ - id
37
+ - created_at
38
+ - updated_at
39
+
40
+ engagement:
41
+ - likes_count
42
+ - comments_count
43
+
44
+ # User-related serializers
45
+
46
+ public_user:
47
+ - with: common_fields # use a single mixin
48
+ - first_name
49
+ - last_name
50
+
51
+ private_user:
52
+ - with: public_user
53
+ - access_token
54
+ - email
55
+
56
+ author:
57
+ - first_name
58
+ - middle_initial
59
+ - last_name
60
+ - joined_at
61
+ - total_posts_count
62
+
63
+ hidden_identity:
64
+ - first_name
65
+ - last_initial
66
+
67
+ # Other Objects/Entities serializers
68
+
69
+ post:
70
+ # include multiple mixins:
71
+ - with:
72
+ - common_fields
73
+ - engagement
74
+ - title
75
+ - body
76
+ # If no serializer is given, all fields will be dumped to the output:
77
+ - widgets
78
+ - comments:
79
+ # If a serializer is given, only the attributes defined in the schema will be included:
80
+ - serializer: comment
81
+ - author:
82
+ - serializer: author
83
+ - alias: author
84
+
85
+ comment:
86
+ - with: common_fields
87
+ - content
88
+ - creator:
89
+ # The root of this node will be "commenter" but the `creator` message will be sent to the `comment` object
90
+ - alias: commenter
91
+ # only include the first name, and last initial
92
+ - serializer: hidden_identity
93
+ ```
94
+
95
+ ### Serializing an Object
96
+
97
+ In your controller, use Donatello to serialize an object according to the schema:
98
+
99
+ ```ruby
100
+ class PostsController < ApplicationController
101
+ # provides the "serialize" method. Note: Just put this in ApplicationController
102
+ include Donatello
103
+
104
+ def index
105
+ render json: serialize(Post.all, :post)
106
+ # or `current_user.posts` or `Post.first`, or a hash like `{ title: "Foo", ... }`
107
+
108
+ # or `render json: { posts: serialize(Post.all) }
109
+ end
110
+ end
111
+ ```
112
+
113
+ This will produce JSON output like:
114
+
115
+ ```JSON
116
+ [{
117
+ "id": "1",
118
+ "title": "How to Defeat Shredder, and Look Good While Doing It.",
119
+ "body": "Once upon a time, in a sewer ...",
120
+ "author": {
121
+ "first_name": "Master",
122
+ "middle_initial": "P",
123
+ "last_name": "Splinter",
124
+ "total_posts_count": 25
125
+ },
126
+ "created_at": "...",
127
+ "updated_at": "...",
128
+ "comments": [{
129
+ "content": "I'll get you Splinter!!!11~!~!",
130
+ "creator": {
131
+ "first_name": "Shred",
132
+ "last_initial": "R"
133
+ }
134
+ // ...
135
+ },{
136
+ // ...
137
+ }],
138
+ "likes_count": 444,
139
+ "comments_count": 33
140
+ },{
141
+ // ...
142
+ }]
143
+ ```
144
+
145
+ ## Contributing
146
+
147
+ Bug reports and pull requests are welcome on GitHub at [https://github.com/devfarm-io/donatello].
148
+
149
+ ## License
150
+
151
+ The gem is available as open source under the terms of the MIT License in this repo.
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[test rubocop]
data/config.ru ADDED
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rubygems"
4
+ require "bundler"
5
+
6
+ Bundler.require :default, :development
7
+
8
+ Combustion.initialize! :all
9
+ run Combustion::Application
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails"
4
+ module Donatello
5
+ # Railtie for incorporating into a rails app
6
+ class Railtie < Rails::Railtie
7
+ initializer "donatello.configure" do |_app|
8
+ Donatello.setup
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Donatello # rubocop:disable Style/Documentation
4
+ MAX_LEVELS = 4 # TODO: make this configurable
5
+
6
+ def serialize(object, schema_name)
7
+ applied = apply_schema(object, schema_name, 0)
8
+ # Don't include the root
9
+ applied ? Oj.dump(applied[schema_name]) : Oj.dump(nil)
10
+ end
11
+
12
+ def apply_schema(object, schema_name, current_level = 0) # rubocop:disable Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
13
+ # Stack level is too deep, return
14
+ return { schema_name => nil } if current_level > MAX_LEVELS || object.nil?
15
+
16
+ schema = Donatello.schema[schema_name.to_s]
17
+
18
+ # Handle empty schemas
19
+ # ex. schema: `empty:`
20
+ return nil if schema.nil?
21
+
22
+ # Handle collections of objects
23
+ if non_hash_enumerable?(object)
24
+ result = object.map do |o|
25
+ apply_schema(o, schema_name, current_level + 1)[schema_name]
26
+ end
27
+ return { schema_name => result }
28
+ end
29
+
30
+ # We can process this schema
31
+ result = schema.inject({}) do |acc, item|
32
+ # TODO: detect cycles
33
+ # TODO: add a test for cycles
34
+ # TODO: add a pretty print to show the stack when stack level too deep
35
+ # TODO: add a pretty print to show the stack when there's a cycle
36
+ if item.is_a?(Hash)
37
+ if item["with"]
38
+ acc.merge(
39
+ handle_with(object, item, current_level)
40
+ )
41
+ else
42
+ acc.merge(
43
+ handle_attribute_config(object, item, current_level)
44
+ )
45
+ end
46
+ elsif object.respond_to?(item)
47
+ acc.merge(
48
+ handle_attribute(object, item)
49
+ )
50
+ else
51
+ handle_exception(object, item)
52
+ end
53
+ end
54
+
55
+ { schema_name => result }
56
+ end
57
+
58
+ private
59
+
60
+ def handle_exception(object, item)
61
+ raise StandardError,
62
+ "Error: Cannot process item - object (#{object.class}) (#{object.inspect}) does not respond to '#{item}'."
63
+ end
64
+
65
+ def handle_attribute(object, item)
66
+ result = object.send(item)
67
+ case result
68
+ when Date, DateTime, Time
69
+ { item => result.iso8601 }
70
+ else
71
+ { item => result }
72
+ end
73
+ end
74
+
75
+ def entry_for(key, item)
76
+ attr_config = item.values.first || {}
77
+ item[key.to_sym] || item[key.to_s] || attr_config[key.to_sym] || attr_config[key.to_s]
78
+ end
79
+
80
+ def handle_attribute_config(object, item, current_level)
81
+ serializer_entry = entry_for(:serializer, item)
82
+ alias_entry = entry_for(:alias, item)
83
+ attribute_name = item.keys.map(&:to_s).find { |k| !%w[alias serializer].include?(k) }
84
+ schema_key = serializer_entry || attribute_name
85
+ alias_key = alias_entry || attribute_name
86
+ sub_object = object.send(attribute_name)
87
+
88
+ { alias_key => apply_schema(sub_object, schema_key, current_level + 1)[schema_key] }
89
+ end
90
+
91
+ def handle_with(object, item, current_level)
92
+ with_entry = item["with"]
93
+ if with_entry.is_a?(String)
94
+ apply_schema(object, with_entry, current_level + 1)[with_entry]
95
+ elsif with_entry.is_a?(Array)
96
+ handle_multiple_with(object, with_entry, current_level)
97
+ else
98
+ {}
99
+ end
100
+ end
101
+
102
+ def handle_multiple_with(object, with_entry, current_level)
103
+ with_entry.inject({}) do |with_combined, with_key|
104
+ res = apply_schema(object, with_key, current_level + 1)[with_key]
105
+ with_combined.merge(res || {})
106
+ end
107
+ end
108
+
109
+ def non_hash_enumerable?(object)
110
+ object.respond_to?(:each) && !object.is_a?(Hash)
111
+ end
112
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Donatello
4
+ VERSION = "0.1.0"
5
+ end
data/lib/donatello.rb ADDED
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "forwardable"
4
+ require "oj"
5
+
6
+ require "donatello/version"
7
+ require "donatello/serializer" # assuming this is your main module
8
+ require "donatello/railtie" if defined?(Rails)
9
+
10
+ module Donatello # rubocop:disable Style/Documentation
11
+ if defined?(Rails)
12
+ Oj.optimize_rails # Optimizes Oj for compatibility with Rails
13
+
14
+ else
15
+ Oj.default_options = {
16
+ use_to_json: true,
17
+ use_as_json: true,
18
+ time_format: :xmlschema,
19
+ second_precision: 3
20
+ }
21
+ Oj.add_to_json
22
+ end
23
+ class << self
24
+ extend Forwardable
25
+
26
+ def setup
27
+ yield config if block_given?
28
+ end
29
+
30
+ def reset!
31
+ @config = nil
32
+ end
33
+
34
+ def config
35
+ @config ||= Config.new
36
+ end
37
+
38
+ def_delegator :config, :schema_location
39
+ def_delegator :config, :schema
40
+ end
41
+
42
+ class Config # rubocop:disable Style/Documentation
43
+ def initialize
44
+ @schema_location = if defined?(Rails)
45
+ Rails.root.join(
46
+ "config", "serialization_schema.yml"
47
+ )
48
+ else
49
+ File.join(Dir.pwd, "config", "serialization_schema.yaml")
50
+ end
51
+ end
52
+
53
+ attr_accessor :schema_location
54
+
55
+ def schema
56
+ @schema ||= YAML.load_file(schema_location)
57
+ end
58
+ end
59
+ end
data/sig/donatello.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Donatello
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: donatello
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Dave Rogers
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-05-08 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: oj
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '3'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '3'
27
+ description: Donatello is a Ruby gem for effortlessly applying YAML-defined serialization
28
+ schemas to Ruby objects, utilizing the speed of the Oj gem for optimal JSON output
29
+ email:
30
+ - dave@devfarm.io
31
+ executables: []
32
+ extensions: []
33
+ extra_rdoc_files: []
34
+ files:
35
+ - ".rubocop.yml"
36
+ - CHANGELOG.md
37
+ - CODE_OF_CONDUCT.md
38
+ - LICENSE.txt
39
+ - README.md
40
+ - Rakefile
41
+ - config.ru
42
+ - lib/donatello.rb
43
+ - lib/donatello/railtie.rb
44
+ - lib/donatello/serializer.rb
45
+ - lib/donatello/version.rb
46
+ - sig/donatello.rbs
47
+ homepage: https://github.com/devfarm-io/donatello
48
+ licenses:
49
+ - MIT
50
+ metadata:
51
+ allowed_push_host: https://rubygems.org
52
+ homepage_uri: https://github.com/devfarm-io/donatello
53
+ source_code_uri: https://github.com/devfarm-io/donatello
54
+ changelog_uri: https://github.com/devfarm-io/donatello/CHANGELOG
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: 3.0.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.5.3
71
+ signing_key:
72
+ specification_version: 4
73
+ summary: Donatello lets you sculpt your serialized JSON according to a YAML schema.
74
+ test_files: []