as_json 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 96ce10484b45434f155d000e40655a2311edce8a7695ca3897a789c257d4a093
4
+ data.tar.gz: 11f911f102ed127fc2b0524353a57526b1d5bdc28945206ddf2427dc9ea06751
5
+ SHA512:
6
+ metadata.gz: c210a1a2719335ab603e6e44baa59e2563b98bbd3f82c0790011ae3598edb0a0e56ee9507f333c36cf2515fda91cb4cbaa8737ef1e8521a8e5562763ddf6fba3
7
+ data.tar.gz: 5e316966a72e7113d57c8c53fe567b23ab6409f2ab53962bb9a6776b55bffcea3982db7fe79f25dc6c74797a8c864ece61387899455e0863786073f288950cbf
@@ -0,0 +1,7 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /tmp/
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.6.5
7
+ before_install: gem install bundler -v 1.17.3
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in as_json.gemspec
4
+ gemspec
5
+
6
+ gem "rake", "~> 12.0"
7
+
8
+ group :development, :test do
9
+ gem "pry"
10
+ end
@@ -0,0 +1,49 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ as_json (0.1.0)
5
+ activemodel (>= 5.0.7.2)
6
+ activesupport (>= 5.0.7.2)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ activemodel (6.0.3.2)
12
+ activesupport (= 6.0.3.2)
13
+ activerecord (6.0.3.2)
14
+ activemodel (= 6.0.3.2)
15
+ activesupport (= 6.0.3.2)
16
+ activesupport (6.0.3.2)
17
+ concurrent-ruby (~> 1.0, >= 1.0.2)
18
+ i18n (>= 0.7, < 2)
19
+ minitest (~> 5.1)
20
+ tzinfo (~> 1.1)
21
+ zeitwerk (~> 2.2, >= 2.2.2)
22
+ coderay (1.1.3)
23
+ concurrent-ruby (1.1.7)
24
+ i18n (1.8.5)
25
+ concurrent-ruby (~> 1.0)
26
+ method_source (1.0.0)
27
+ minitest (5.14.1)
28
+ pry (0.13.1)
29
+ coderay (~> 1.1)
30
+ method_source (~> 1.0)
31
+ rake (12.3.3)
32
+ sqlite3 (1.4.2)
33
+ thread_safe (0.3.6)
34
+ tzinfo (1.2.7)
35
+ thread_safe (~> 0.1)
36
+ zeitwerk (2.4.0)
37
+
38
+ PLATFORMS
39
+ ruby
40
+
41
+ DEPENDENCIES
42
+ activerecord (>= 5.0.7.2)
43
+ as_json!
44
+ pry
45
+ rake (~> 12.0)
46
+ sqlite3 (>= 1.4.2)
47
+
48
+ BUNDLED WITH
49
+ 1.17.3
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Upscope
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 all
13
+ 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 THE
21
+ SOFTWARE.
@@ -0,0 +1,57 @@
1
+ # AsJson
2
+ [![Build Status](https://travis-ci.org/upscopeio/as_json.svg?branch=master)](https://travis-ci.org/upscopeio/as_json)
3
+
4
+ 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/as_json`. To experiment with that code, run `bin/console` for an interactive prompt.
5
+
6
+ ## Installation
7
+
8
+ Add this line to your application's Gemfile:
9
+
10
+ ```ruby
11
+ gem 'as_json'
12
+ ```
13
+
14
+ And then execute:
15
+
16
+ $ bundle
17
+
18
+ Or install it yourself as:
19
+
20
+ $ gem install as_json
21
+
22
+ ## Usage
23
+ Including the `AsJson` module in your models you will have access to the `json_with` method, allowing you to define which attributes/methods should be converted to JSON
24
+
25
+ ``` ruby
26
+ # app/models/team.rb
27
+ class Team < ApplicationRecord
28
+ include AsJson
29
+
30
+ json_with :name
31
+ end
32
+
33
+
34
+ # app/models/user.rb
35
+ class User < ApplicationRecord
36
+ include AsJson
37
+
38
+ belongs_to :team
39
+
40
+ json_with :name, team: [:name]
41
+ end
42
+
43
+ team = Team.create name: 'Acme'
44
+ user = User.create name: 'John Doe', team: team
45
+ user.as_json
46
+ # => {'name' => 'John Doe', 'team' => { 'name' => 'Acme', '_type' => 'team'}, '_type' => 'user' }
47
+ ```
48
+
49
+ ## Development
50
+
51
+ 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.
52
+
53
+ 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).
54
+
55
+ ## Contributing
56
+
57
+ Bug reports and pull requests are welcome on GitHub at https://github.com/upscopeio/as_json.
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ desc "Run unit tests"
7
+ task default: :test
8
+
9
+ desc "Test AsJson"
10
+ Rake::TestTask.new(:test) do |t|
11
+ t.libs << "test"
12
+ t.pattern = "test/**/*_test.rb"
13
+ t.verbose = true
14
+ end
@@ -0,0 +1,31 @@
1
+ require_relative 'lib/as_json/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "as_json"
5
+ spec.version = AsJson::VERSION
6
+ spec.authors = ["Pablo Fonseca", "Joe d'Elia"]
7
+ spec.email = ["pablofonseca777@gmail.com", "joe@delia.is"]
8
+
9
+ spec.summary = %q{Write a short summary, because RubyGems requires one.}
10
+ spec.description = %q{Write a longer description or delete this line.}
11
+ spec.homepage = "https://github.com/upscopeio/as_json"
12
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
13
+
14
+ spec.metadata["homepage_uri"] = spec.homepage
15
+ spec.metadata["source_code_uri"] = spec.homepage
16
+
17
+ # Specify which files should be added to the gem when it is released.
18
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
19
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
20
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
21
+ end
22
+ spec.bindir = "exe"
23
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
24
+ spec.require_paths = ["lib"]
25
+
26
+ spec.add_dependency "activesupport", ">= 5.0.7.2"
27
+ spec.add_dependency "activemodel", ">= 5.0.7.2"
28
+
29
+ spec.add_development_dependency "activerecord", ">= 5.0.7.2"
30
+ spec.add_development_dependency "sqlite3", ">= 1.4.2"
31
+ end
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "as_json"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
@@ -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,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'as_json/version'
4
+ require 'as_json/json_encoder'
5
+ require 'as_json/scoped_json_mapper'
6
+
7
+ require 'active_support/concern'
8
+ require 'active_support/json'
9
+ require 'active_support/core_ext/object'
10
+
11
+ module AsJson
12
+ extend ActiveSupport::Concern
13
+
14
+ class_methods do
15
+ def default_json_attributes
16
+ @default_json_attributes
17
+ end
18
+
19
+ def json_with(*attributes, **kargs)
20
+ if @default_json_attributes.blank?
21
+ kargs = { _base: attributes }.merge(kargs)
22
+ @default_json_attributes = kargs
23
+ else
24
+ @default_json_attributes[:_base] += attributes
25
+ @default_json_attributes = AsJson.merge_default_attributes(
26
+ @default_json_attributes, kargs
27
+ )
28
+ end
29
+ ScopedJsonMapper.new self
30
+ end
31
+ end
32
+
33
+ def self.merge_default_attributes(existing, new_attributes)
34
+ existing.deep_merge(new_attributes) do |_k, oldval, newval|
35
+ if [oldval, newval].all? { |value| value.is_a?(Array) }
36
+ oldval + newval
37
+ elsif oldval.is_a?(Array) && newval.is_a?(Hash)
38
+ oldval = oldval.map { |k| [k, true] }.to_h
39
+ oldval.deep_merge newval
40
+ elsif newval.is_a?(Array) && oldval.is_a?(Hash)
41
+ newval = newval.map { |k| [k, true] }.to_h
42
+ oldval.deep_merge newval
43
+ else
44
+ newval
45
+ end
46
+ end
47
+ end
48
+
49
+ def as_json(opts = {})
50
+ JsonEncoder.new(self, opts).json
51
+ end
52
+ end
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AsJson
4
+ class JsonEncoder
5
+ def initialize(object, options)
6
+ @object = object
7
+ @options = as_json_options(options)
8
+ @subobject_attributes = {}
9
+ end
10
+
11
+ def json
12
+ json = attributes_to_encode.map do |attribute, method|
13
+ if attribute == method && @object.respond_to?(method)
14
+ [clean_json_key(attribute.to_s), @object.send(method).as_json(subobjects_as_json_options(attribute))]
15
+ else
16
+ value = method.is_a?(Proc) ? @object.instance_exec(&method) : @object.send(method)
17
+ [clean_json_key(attribute.to_s), value.as_json(subobjects_as_json_options)]
18
+ end
19
+ end.to_h
20
+
21
+ json['id'] = @object.hashed_id if @object.respond_to?(:hashed_id) && json['id'].blank?
22
+ json = json.sort_by { |k, _v| k == 'id' ? '_id' : k }.to_h
23
+ json['_type'] = @object.class.name.underscore
24
+ json.except(*[@options[:without] || []].flatten.map(&:to_s))
25
+ end
26
+
27
+ private
28
+
29
+ def subobjects_as_json_options(object = nil)
30
+ options = {}
31
+ options.merge!({ _default_attributes: @subobject_attributes[object.to_sym] }) if object && @subobject_attributes[object.to_sym]
32
+ options.merge!(@options.except(:_default_attributes, :only, :without, :with))
33
+ end
34
+
35
+ def clean_json_key(key)
36
+ key = key[0..-2] if key.end_with?('?')
37
+ key
38
+ end
39
+
40
+ def as_json_options(opts)
41
+ opts[:_default_attributes] ||= @object.class.default_json_attributes
42
+ return opts if opts[:with_only].blank?
43
+
44
+ opts[:with] = opts[:with_only]
45
+ opts[:only] = opts[:with_only]
46
+ opts
47
+ end
48
+
49
+ def attributes_to_encode
50
+ attrs = [@options[:with] || []].flatten.map { |attr| [attr, attr] }
51
+ add_defaults_to_attributes(attrs, @options[:_default_attributes]) if @options[:_default_attributes].present?
52
+
53
+ attrs = attrs.select { |attr, _| attr.in? [@options[:only]].flatten } if @options[:only].present?
54
+ attrs = attrs.reject { |attr, _| attr.in? [@options[:without]].flatten } if @options[:without].present?
55
+ attrs
56
+ end
57
+
58
+ def add_defaults_to_attributes(attrs, default_attributes)
59
+ default_attributes.each do |scope, scoped_attributes|
60
+ if scope == :_base
61
+ # These are just default attributes
62
+ attrs.push(*scoped_attributes.map { |a| [a, a] })
63
+ elsif (scoped_attributes.is_a?(Array) || scoped_attributes.is_a?(Hash)) && !scope.to_s.start_with?('with_')
64
+ # These are associations with sub configuration
65
+ attrs.push([scope, scope])
66
+ @subobject_attributes[scope] = if scoped_attributes.is_a?(Hash)
67
+ scoped_attributes
68
+ else
69
+ { _base: scoped_attributes }
70
+ end
71
+ elsif !scope.to_s.start_with?('with_')
72
+ # These are aliases for a different method
73
+ attrs.push([scope, scoped_attributes == true ? scope : scoped_attributes])
74
+ elsif @options[scope] || @options[:with_everything] == true
75
+ # This is if the options include with_xyz
76
+ scoped_attributes = { _base: [scoped_attributes].flatten } unless scoped_attributes.is_a?(Hash)
77
+ add_defaults_to_attributes attrs, scoped_attributes
78
+ end
79
+ end
80
+ end
81
+ end
82
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AsJson
4
+ class ScopedJsonMapper
5
+ def initialize(klass)
6
+ @klass = klass
7
+ end
8
+
9
+ def method_missing(name, *args, **kargs)
10
+ @klass.json_with "with_#{name}": kargs.merge(args.map { |key| [key, true] }.to_h)
11
+ end
12
+
13
+ def respond_to_missing?
14
+ true
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,3 @@
1
+ module AsJson
2
+ VERSION = "0.1.0"
3
+ end
metadata ADDED
@@ -0,0 +1,116 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: as_json
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Pablo Fonseca
8
+ - Joe d'Elia
9
+ autorequire:
10
+ bindir: exe
11
+ cert_chain: []
12
+ date: 2020-08-19 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: activesupport
16
+ requirement: !ruby/object:Gem::Requirement
17
+ requirements:
18
+ - - ">="
19
+ - !ruby/object:Gem::Version
20
+ version: 5.0.7.2
21
+ type: :runtime
22
+ prerelease: false
23
+ version_requirements: !ruby/object:Gem::Requirement
24
+ requirements:
25
+ - - ">="
26
+ - !ruby/object:Gem::Version
27
+ version: 5.0.7.2
28
+ - !ruby/object:Gem::Dependency
29
+ name: activemodel
30
+ requirement: !ruby/object:Gem::Requirement
31
+ requirements:
32
+ - - ">="
33
+ - !ruby/object:Gem::Version
34
+ version: 5.0.7.2
35
+ type: :runtime
36
+ prerelease: false
37
+ version_requirements: !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - ">="
40
+ - !ruby/object:Gem::Version
41
+ version: 5.0.7.2
42
+ - !ruby/object:Gem::Dependency
43
+ name: activerecord
44
+ requirement: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: 5.0.7.2
49
+ type: :development
50
+ prerelease: false
51
+ version_requirements: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - ">="
54
+ - !ruby/object:Gem::Version
55
+ version: 5.0.7.2
56
+ - !ruby/object:Gem::Dependency
57
+ name: sqlite3
58
+ requirement: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: 1.4.2
63
+ type: :development
64
+ prerelease: false
65
+ version_requirements: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - ">="
68
+ - !ruby/object:Gem::Version
69
+ version: 1.4.2
70
+ description: Write a longer description or delete this line.
71
+ email:
72
+ - pablofonseca777@gmail.com
73
+ - joe@delia.is
74
+ executables: []
75
+ extensions: []
76
+ extra_rdoc_files: []
77
+ files:
78
+ - ".gitignore"
79
+ - ".travis.yml"
80
+ - Gemfile
81
+ - Gemfile.lock
82
+ - LICENSE
83
+ - README.md
84
+ - Rakefile
85
+ - as_json.gemspec
86
+ - bin/console
87
+ - bin/setup
88
+ - lib/as_json.rb
89
+ - lib/as_json/json_encoder.rb
90
+ - lib/as_json/scoped_json_mapper.rb
91
+ - lib/as_json/version.rb
92
+ homepage: https://github.com/upscopeio/as_json
93
+ licenses: []
94
+ metadata:
95
+ homepage_uri: https://github.com/upscopeio/as_json
96
+ source_code_uri: https://github.com/upscopeio/as_json
97
+ post_install_message:
98
+ rdoc_options: []
99
+ require_paths:
100
+ - lib
101
+ required_ruby_version: !ruby/object:Gem::Requirement
102
+ requirements:
103
+ - - ">="
104
+ - !ruby/object:Gem::Version
105
+ version: 2.3.0
106
+ required_rubygems_version: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ requirements: []
112
+ rubygems_version: 3.1.4
113
+ signing_key:
114
+ specification_version: 4
115
+ summary: Write a short summary, because RubyGems requires one.
116
+ test_files: []