safe_object_as_json 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c5cfc9f52cea679fdbd39e375fd930f28c9f87f09a636fab4765053c0a5bec84
4
+ data.tar.gz: 02fd5931b21822ea69643ef8ed47069d055b38a3d15a39b41b70b81829c046bf
5
+ SHA512:
6
+ metadata.gz: 63e3e7ec587ac6fa99438bd7419b886ea4d0bb2eb8d74763d3de8c60200f8a6c701bb3e9e4e0b2074aee8c36cb8717346602f792adc0d616b26808eaffa8a4de
7
+ data.tar.gz: e856a2199351f45be79f0abab0a0eac31af2424b9e6fe9370e215617ba358ce3199558c5e35ffa0813d45a345ed9a24081e91829e5ba67062914db088d226357
data/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+ All notable changes to this project will be documented in this file.
3
+
4
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## 1.0.0
8
+
9
+ ### Added
10
+ - Re-implement Object#as_json to omit circular dependencies in internal object references.
11
+ - Omit Proc and IO objects from being included in Object#as_json result.
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2021 Brian Durand
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,44 @@
1
+ [![Continuous Integration](https://github.com/bdurand/safe_object_as_json/actions/workflows/continuous_integration.yml/badge.svg)](https://github.com/bdurand/safe_object_as_json/actions/workflows/continuous_integration.yml)
2
+ [![Ruby Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://github.com/testdouble/standard)
3
+
4
+ # Safe Object As JSON
5
+
6
+ This gem provides an enhancement to the implementation for `as_json` on the core `Object` class in the ActiveSiupport library. The implementation provided by ActiveSupport dumps the instance variables as name value pairs in a Hash. However, this is susceptible to infinite recursion when dumping an object that maintains references to other objects that then maintain back references to the original object.
7
+
8
+ The fix provided by this gem maintains a state of the current stack of objects being used to construct the `as_json` hash. If an object has already been referenced in the current call to `Object#as_json`, it is left out of the hash in lieu of having it raise a stack level too deep error.
9
+
10
+ It also omits any `Proc` or `IO` references since these are inherently not serializable.
11
+
12
+ ## Usage
13
+
14
+ No changes are needed to use this gem. It will just replace the method definition of `Object#as_json`. It will not impact any class that defines its own `as_json` or `to_hash` method which includes all the core Ruby classes (String, Numeric, Array, Hash) as well as ActiveModel classes.
15
+
16
+ The `Object#as_json` method is really just a fallback method that exists so that all objects can be sent to a JSON serializer. If you do have classes that rely on this method, you should really just implement the `as_json` method yourself. The main reason this gem exists is to handle cases where you don't control the class definition in your application code.
17
+
18
+ ## Installation
19
+
20
+ Add this line to your application's Gemfile:
21
+
22
+ ```ruby
23
+ gem 'safe_object_as_json'
24
+ ```
25
+
26
+ And then execute:
27
+ ```bash
28
+ $ bundle
29
+ ```
30
+
31
+ Or install it yourself as:
32
+ ```bash
33
+ $ gem install safe_object_as_json
34
+ ```
35
+
36
+ ## Contributing
37
+
38
+ Open a pull request on GitHub.
39
+
40
+ Please use the [standardrb](https://github.com/testdouble/standard) syntax and lint your code with `standardrb --fix` before submitting.
41
+
42
+ ## License
43
+
44
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 1.0.0
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/all"
4
+
5
+ module SafeObjectAsJson
6
+ # ActiveSupport 7 is adding support for filtering hash values with :only and :except options.
7
+ SUPPORT_FILTERING = (ActiveSupport.version.canonical_segments.first > 6)
8
+
9
+ VERSION = File.read(File.expand_path("../VERSION", __dir__)).chomp
10
+ end
11
+
12
+ class Object
13
+ # Converts any object to JSON by creating a hash out of it's instance variables.
14
+ # If there is a circular reference within an object hierarchy, then duplicate
15
+ # objects will be omitted in order to avoid infinite recursion.
16
+ def as_json(options = nil)
17
+ if respond_to?(:to_hash)
18
+ to_hash.as_json(options)
19
+ else
20
+ # The default as_json serializer serializes the instance variables as name value pairs.
21
+ # In order to prevent infinite recursion, we keep track of the object already used
22
+ # in the serialization and omit them if they are included recursively.
23
+ references = (Thread.current[:object_as_json_references] || Set.new)
24
+ begin
25
+ Thread.current[:object_as_json_references] = references if references.empty?
26
+ references << object_id
27
+ hash = {}
28
+
29
+ # Apply :only and :except filter from the options to the hash of instance variables.
30
+ values = instance_values
31
+ if options && SafeObjectAsJson::SUPPORT_FILTERING
32
+ only_attr = options[:only]
33
+ if only_attr
34
+ values = values.slice(*Array(only_attr).map(&:to_s))
35
+ else
36
+ except_attr = options[:except]
37
+ if except_attr
38
+ values = values.except(*Array(except_attr).map(&:to_s))
39
+ end
40
+ end
41
+ end
42
+
43
+ values.each do |name, value|
44
+ unless references.include?(value.object_id) || value.is_a?(Proc) || value.is_a?(IO)
45
+ references << value
46
+ hash[name] = (options.nil? ? value.as_json : value.as_json(options.dup))
47
+ end
48
+ end
49
+ hash
50
+ ensure
51
+ references.delete(object_id)
52
+ Thread.current[:object_as_json_references] = nil if references.empty?
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,35 @@
1
+ Gem::Specification.new do |spec|
2
+ spec.name = "safe_object_as_json"
3
+ spec.version = File.read(File.expand_path("../VERSION", __FILE__)).strip
4
+ spec.authors = ["Brian Durand"]
5
+ spec.email = ["bbdurand@gmail.com"]
6
+
7
+ spec.summary = "Drop in replacement for the Object#as_json implementation in ActiveSupport, but with logic to handle circular references between objects to avoid infinite recursion."
8
+ spec.homepage = "https://github.com/bdurand/safe_object_as_json"
9
+ spec.license = "MIT"
10
+
11
+ # Specify which files should be added to the gem when it is released.
12
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
13
+ ignore_files = %w[
14
+ .
15
+ Appraisals
16
+ Gemfile
17
+ Gemfile.lock
18
+ Rakefile
19
+ bin/
20
+ gemfiles/
21
+ spec/
22
+ web_ui.png
23
+ ]
24
+ spec.files = Dir.chdir(File.expand_path("..", __FILE__)) do
25
+ `git ls-files -z`.split("\x0").reject { |f| ignore_files.any? { |path| f.start_with?(path) } }
26
+ end
27
+
28
+ spec.require_paths = ["lib"]
29
+
30
+ spec.add_dependency "activesupport"
31
+
32
+ spec.add_development_dependency "bundler"
33
+
34
+ spec.required_ruby_version = ">= 2.5"
35
+ end
metadata ADDED
@@ -0,0 +1,78 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: safe_object_as_json
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Brian Durand
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2021-07-29 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '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'
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ description:
42
+ email:
43
+ - bbdurand@gmail.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - CHANGELOG.md
49
+ - MIT-LICENSE
50
+ - README.md
51
+ - VERSION
52
+ - lib/safe_object_as_json.rb
53
+ - safe_object_as_json.gemspec
54
+ homepage: https://github.com/bdurand/safe_object_as_json
55
+ licenses:
56
+ - MIT
57
+ metadata: {}
58
+ post_install_message:
59
+ rdoc_options: []
60
+ require_paths:
61
+ - lib
62
+ required_ruby_version: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: '2.5'
67
+ required_rubygems_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: '0'
72
+ requirements: []
73
+ rubygems_version: 3.0.3
74
+ signing_key:
75
+ specification_version: 4
76
+ summary: Drop in replacement for the Object#as_json implementation in ActiveSupport,
77
+ but with logic to handle circular references between objects to avoid infinite recursion.
78
+ test_files: []