rails_json_serializer 1.1.4 → 3.0.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b6b2c3e2e7b905079dce0ddbbf0b48028a36d68b10da5ab4278d597eaf70713a
4
- data.tar.gz: 9e730e031d3b73eaa9fb27f838fb4f6761256755281257cb99db9b3b15659ded
3
+ metadata.gz: 8edc4939ddb0eea8b4cfa1b78201c49c2f80c38af19abaad305d0305054b16f6
4
+ data.tar.gz: f58eb0af13e90363a900ef5b461b34aa3b8b04805a6b568d931961c65133347d
5
5
  SHA512:
6
- metadata.gz: 70bba5bd544d0d2e95ae9bec6b5c4762eec9b036fe750a0777ef7663903b9894e05f8c2fcb703f2d021023594132ab2d6d6cecea4a1d8e2c12a3b72dd1c1d7e2
7
- data.tar.gz: 27594e6cb05baefffd863555b226f2b672a3c84dcebbb661672266cba0ede47181efe39e702b7a44872582b0a873d5957e91200b4e8a1c6ef34aaf3f76abba98
6
+ metadata.gz: dbf6909c1a77f2317757a3d23cbb0deedceb9ea2a0e2d151e902bc1633afb74574bd70c3ed65a5e38a32f90a76a1700507b50dbeabdf6419cd32dc873ac2eb9f
7
+ data.tar.gz: b3a37898f3a22d3be435d094bf22c4bb939bae693c033612b8477c292d8f97c14be09c91a7a6b179be0edb5d014d3c57f6fc686ed4ce2ef51d15cf3f131583ec
data/lib/serializer.rb CHANGED
@@ -1,8 +1,6 @@
1
- require 'active_support/concern'
2
- require_relative 'serializer/application_serializer'
1
+ require_relative 'serializer/model_serializer'
3
2
  Dir[File.join(Rails.root, 'app', 'serializers', '**', '*.rb')].each {|file| require file }
4
3
  require_relative 'serializer/configuration'
5
- require_relative 'serializer/concern'
6
4
 
7
5
  module Serializer
8
6
  # config src: http://lizabinante.com/blog/creating-a-configurable-ruby-gem/
@@ -24,4 +22,4 @@ module Serializer
24
22
  end
25
23
 
26
24
  # include the extension
27
- ActiveRecord::Base.send(:include, Serializer::Concern)
25
+ # ActiveRecord::Base.send(:include, Serializer::Concern)
@@ -0,0 +1,202 @@
1
+ module ModelSerializer
2
+ # klazz is that class object that included this module
3
+ def self.included klass
4
+ # START CLASS EVAL
5
+ klass.class_eval do
6
+
7
+ # Rails 5 has autoloading issues with modules. They will show as not defined, when available.
8
+ if Rails.env.development?
9
+ begin
10
+ "#{klass.name}Serializer".constantize
11
+ rescue NameError => e
12
+ end
13
+ end
14
+
15
+ if self.const_defined?("#{klass.name}Serializer")
16
+ serializer_klass = "#{klass.name}Serializer".constantize
17
+ serializer_query_names = serializer_klass.public_instance_methods
18
+ if klass.superclass.const_defined?("SERIALIZER_QUERY_KEYS_CACHE")
19
+ self.const_set('SERIALIZER_QUERY_KEYS_CACHE', (serializer_query_names + klass.superclass::SERIALIZER_QUERY_KEYS_CACHE).uniq)
20
+ else
21
+ self.const_set('SERIALIZER_QUERY_KEYS_CACHE', serializer_query_names)
22
+ end
23
+ # Inject class methods, will have access to those queries on the class.
24
+ klass.send(:extend, serializer_klass)
25
+
26
+ # no need to define it if inheriting class has defined it OR has been manually overridden.
27
+ # CLASS METHODS
28
+ klass.send(:define_singleton_method, :serializer) do |opts = {}|
29
+ query = opts[:json_query_override].present? ? self.send(opts[:json_query_override], opts) : serializer_query(opts)
30
+ if Serializer.configuration.enable_includes && query[:include].present? && !opts[:skip_eager_loading]
31
+ includes(generate_includes_from_json_query(query)).as_json(query)
32
+ else
33
+ # Have to use 'all' gets stack level too deep otherwise. Not sure why.
34
+ all.as_json(query)
35
+ end
36
+ end
37
+
38
+ klass.send(:define_singleton_method, :generate_includes_from_json_query) do |options = {}, klass = nil|
39
+ query_filter = {}
40
+ klass = self if klass.nil?
41
+ if options[:include].present? && !options[:skip_eager_loading]
42
+ options[:include].each do |include_key, include_hash|
43
+ next if include_hash[:skip_eager_loading] == true
44
+ # Will 'next' if there is a scope that takes arguments, an instance-dependent scope.
45
+ # Can't eager load when assocation has a instance condition for it's associative scope.
46
+ # Might not be a real assocation
47
+ next if klass.reflect_on_association(include_key).nil?
48
+ next if klass.reflect_on_association(include_key).scope&.arity&.nonzero?
49
+ query_filter[include_key] = {}
50
+ next if include_hash.none?
51
+ query_filter[include_key] = generate_includes_from_json_query(include_hash, klass.reflect_on_association(include_key).klass)
52
+ end
53
+ end
54
+ # Does not include data, just eager-loads. Useful when methods need assocations, but you don't need association data.
55
+ if options[:eager_include].present?
56
+ options[:eager_include].each do |include_key|
57
+ # Will 'next' if there is a scope that takes arguments, an instance-dependent scope.
58
+ # Can't eager load when assocation has a instance condition for it's associative scope.
59
+ # Might not be a real assocation
60
+ next if klass.reflect_on_association(include_key).nil?
61
+ next if klass.reflect_on_association(include_key).scope&.arity&.nonzero?
62
+ query_filter[include_key] ||= {}
63
+ end
64
+ end
65
+ return query_filter
66
+ end
67
+
68
+ klass.send(:define_singleton_method, :as_json_associations_alias_fix) do |options, data, opts = {}|
69
+ if data
70
+ # Depth is almost purely for debugging purposes
71
+ opts[:depth] ||= 0
72
+ if options[:include].present?
73
+ options[:include].each do |include_key, include_hash|
74
+ # The includes doesn't have to have a hash attached. Skip it if it doesn't.
75
+ next if include_hash.nil?
76
+ data_key = include_key.to_s
77
+ if include_hash[:as].present?
78
+ if include_hash[:as].to_s == include_key.to_s
79
+ raise "Serializer: Cannot alias json query association to have the same as the original key; as: #{include_hash[:as].to_s}; original_key: #{include_key.to_s} on self: #{name}"
80
+ end
81
+ alias_name = include_hash[:as]
82
+ data[alias_name.to_s] = data[include_key.to_s]
83
+ data.delete(include_key.to_s)
84
+ data_key = alias_name.to_s
85
+ end
86
+ # At this point, the data could be an array of objects, with no as_json options.
87
+ if !data[data_key].is_a?(Array)
88
+ data[data_key] = as_json_associations_alias_fix(include_hash, data[data_key], {depth: opts[:depth] + 1})
89
+ else
90
+ data[data_key].each_with_index do |value,i|
91
+ data[data_key][i] = as_json_associations_alias_fix(include_hash, value, {depth: opts[:depth] + 1})
92
+ end
93
+ end
94
+ end
95
+ end
96
+ end
97
+ return data
98
+ end
99
+
100
+ # no need to define it if inheriting class has defined it OR has been manually overridden.
101
+ # INSTANCE Methods
102
+
103
+
104
+ klass.send(:define_method, :as_json) do |options = {}|
105
+ # We don't need to run this custom `as_json` multiple times, if defined on inherited class.
106
+ if options[:ran_serialization]
107
+ return super(options)
108
+ end
109
+ options[:ran_serialization] = true
110
+ # Not caching records that don't have IDs.
111
+ if !Serializer.configuration.disable_model_caching && self.id && options[:cache_key].present? && !(options.key?(:cache_for) && options[:cache_for].nil?)
112
+ cache_key = "#{self.class.name}_____#{options[:cache_key]}___#{self.id}"
113
+ if Rails.cache.exist?(cache_key)
114
+ Rails.logger.info "Serializer: Cache reading #{cache_key}" if Serializer.configuration.debug
115
+ return Rails.cache.read(cache_key)
116
+ else
117
+ data = super(options)
118
+ data = self.class.as_json_associations_alias_fix(options, data)
119
+ begin
120
+ Rails.logger.info "Serializer: Caching #{cache_key} for #{(options[:cache_for] || Serializer.configuration.default_cache_time)} minutes." if Serializer.configuration.debug
121
+ Rails.cache.write(cache_key, data, expires_in: (options[:cache_for] || Serializer.configuration.default_cache_time).minute)
122
+ rescue Exception => e
123
+ Rails.logger.error "Serializer: Internal Server Error on #{self.class}#as_json ID: #{self.id} for cache key: #{cache_key}"
124
+ Rails.logger.error e.class
125
+ Rails.logger.error e.message
126
+ Rails.logger.error e.backtrace
127
+ end
128
+ return data
129
+ end
130
+ else
131
+ if Serializer.configuration.debug && !Serializer.configuration.disable_model_caching && self.id && options[:cache_key].present? && options.key?(:cache_for) && options[:cache_for].nil?
132
+ Rails.logger.info "Serializer: Caching #{cache_key} NOT caching due to `cache_for: nil`"
133
+ end
134
+ data = super(options)
135
+ data = self.class.as_json_associations_alias_fix(options, data)
136
+ return data
137
+ end
138
+ end
139
+
140
+ if !klass.method_defined?(:serializer)
141
+ klass.send(:define_method, :serializer) do |opts = {}|
142
+ query = opts[:json_query_override].present? ? self.class.send(opts[:json_query_override], opts) : self.class.serializer_query(opts)
143
+ if Serializer.configuration.enable_includes && query[:include].present? && self.class.column_names.include?('id') && self.id.present? && !opts[:skip_eager_loading] && self.respond_to?(:persisted?) && self.persisted?
144
+ # It's an extra SQL call, but most likely worth it to pre-load associations
145
+ self.class.includes(self.class.generate_includes_from_json_query(query)).find(self.id).as_json(query)
146
+ else
147
+ as_json(query)
148
+ end
149
+ end
150
+ end
151
+
152
+ # # SHOULD NOT BE OVERRIDDEN.
153
+ klass.send(:define_method, :clear_serializer_cache) do
154
+ if self.class.const_defined?("SERIALIZER_QUERY_KEYS_CACHE")
155
+ self.class::SERIALIZER_QUERY_KEYS_CACHE.each do |query_name|
156
+ cache_key = "#{self.class.name}_____#{query_name}___#{self.id}"
157
+ Rails.logger.info "Serializer: CLEARING CACHE KEY: #{cache_key}" if Serializer.configuration.debug
158
+ Rails.cache.delete(cache_key)
159
+ end
160
+ return true
161
+ else
162
+ # if Serializer.configuration.debug
163
+ Rails.logger.error(
164
+ """
165
+ ERROR. COULD NOT CLEAR SERIALIZER CACHE FOR: Class #{self.class.name}
166
+ Serializer: Class #{self.class.name} may not have the serializer module #{self.class.name}Serializer defined.
167
+ Nor was it defined on an inheriting class.
168
+ """
169
+ )
170
+ # end
171
+ return nil
172
+ end
173
+ end
174
+
175
+ serializer_query_names.each do |query_name|
176
+ serializer_name = query_name[/(?<name>.+)_query/, :name]
177
+ if serializer_name.nil?
178
+ Rails.logger.error "Serializer: #{serializer_klass.name} method #{query_name} does not end in '(.+)_query', as is expected of serializers" if Serializer.configuration.debug
179
+ next
180
+ end
181
+ if serializer_name == 'serializer'
182
+ # No longer necessary to add here. We've added them above.
183
+ # klass.send(:define_method, serializer_name) do |opts = {}|
184
+ # super({json_query_override: query_name}.merge(opts))
185
+ # end
186
+ # klass.send(:define_singleton_method, serializer_name) do |opts = {}|
187
+ # super({json_query_override: query_name}.merge(opts))
188
+ # end
189
+ else
190
+ klass.send(:define_method, serializer_name) do |opts = {}|
191
+ serializer({json_query_override: query_name}.merge(opts))
192
+ end
193
+ klass.send(:define_singleton_method, serializer_name) do |opts = {}|
194
+ serializer({json_query_override: query_name}.merge(opts))
195
+ end
196
+ end
197
+ end
198
+ end
199
+ end
200
+ # END CLASS EVAL
201
+ end
202
+ end
metadata CHANGED
@@ -1,11 +1,11 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rails_json_serializer
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.1.4
4
+ version: 3.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - benjamin.dana.software.dev@gmail.com
8
- autorequire:
8
+ autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
11
  date: 2020-04-22 00:00:00.000000000 Z
@@ -16,28 +16,28 @@ dependencies:
16
16
  requirements:
17
17
  - - "~>"
18
18
  - !ruby/object:Gem::Version
19
- version: '5.1'
19
+ version: '6.1'
20
20
  type: :runtime
21
21
  prerelease: false
22
22
  version_requirements: !ruby/object:Gem::Requirement
23
23
  requirements:
24
24
  - - "~>"
25
25
  - !ruby/object:Gem::Version
26
- version: '5.1'
26
+ version: '6.1'
27
27
  - !ruby/object:Gem::Dependency
28
28
  name: rails
29
29
  requirement: !ruby/object:Gem::Requirement
30
30
  requirements:
31
31
  - - "~>"
32
32
  - !ruby/object:Gem::Version
33
- version: '5.1'
33
+ version: '5.0'
34
34
  type: :development
35
35
  prerelease: false
36
36
  version_requirements: !ruby/object:Gem::Requirement
37
37
  requirements:
38
38
  - - "~>"
39
39
  - !ruby/object:Gem::Version
40
- version: '5.1'
40
+ version: '5.0'
41
41
  - !ruby/object:Gem::Dependency
42
42
  name: rspec
43
43
  requirement: !ruby/object:Gem::Requirement
@@ -108,21 +108,20 @@ dependencies:
108
108
  - - "~>"
109
109
  - !ruby/object:Gem::Version
110
110
  version: '1.4'
111
- description:
112
- email:
111
+ description:
112
+ email:
113
113
  executables: []
114
114
  extensions: []
115
115
  extra_rdoc_files: []
116
116
  files:
117
117
  - lib/serializer.rb
118
- - lib/serializer/application_serializer.rb
119
- - lib/serializer/concern.rb
120
118
  - lib/serializer/configuration.rb
119
+ - lib/serializer/model_serializer.rb
121
120
  homepage: https://github.com/danabr75/rails_json_serializer
122
121
  licenses:
123
122
  - LGPL-3.0-only
124
123
  metadata: {}
125
- post_install_message:
124
+ post_install_message:
126
125
  rdoc_options: []
127
126
  require_paths:
128
127
  - lib
@@ -138,7 +137,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
138
137
  version: '0'
139
138
  requirements: []
140
139
  rubygems_version: 3.0.8
141
- signing_key:
140
+ signing_key:
142
141
  specification_version: 4
143
142
  summary: An ActiveRecord JSON Serializer with supported caching and eager-loading
144
143
  test_files: []
@@ -1,10 +0,0 @@
1
- module ApplicationSerializer
2
- def serializer_query opts = {}
3
- {
4
- include: {
5
- },
6
- methods: %w(),
7
- cache_key: __callee__,
8
- }
9
- end
10
- end
@@ -1,232 +0,0 @@
1
- module Serializer
2
- DELETE_MATCHED_SUPPORTED_CACHE_TYPES = [:memory_store, :file_store]
3
- module Concern
4
- # ActiveSupport extend src: https://stackoverflow.com/questions/2328984/rails-extending-activerecordbase
5
- extend ActiveSupport::Concern
6
-
7
- # START MODEL INSTANCE METHODS
8
- def clear_serializer_cache
9
- if self.class.const_defined?("SERIALIZER_QUERY_KEYS_CACHE")
10
-
11
- # list_of_serializer_query_names = "#{self.class.name}::SERIALIZER_QUERY_KEYS_CACHE".constantize
12
- self.class.get_cumulatively_inherited_serializer_query_list.each do |query_name|
13
- cache_key = "#{self.class.name}_____#{query_name}___#{self.id}"
14
- Rails.logger.info "Serializer: CLEARING CACHE KEY: #{cache_key}" if Serializer.configuration.debug
15
- Rails.cache.delete(cache_key)
16
- end
17
- return true
18
- else
19
- # if Serializer.configuration.debug
20
- Rails.logger.error(
21
- """
22
- ERROR. COULD NOT CLEAR SERIALIZER CACHE FOR: Class #{self.class.name}
23
- Serializer: Class #{self.class.name} may not have the serializer module #{self.class.name}Serializer defined.
24
- Nor was it defined on an inheriting class.
25
- """
26
- )
27
- # end
28
- return nil
29
- end
30
- end
31
-
32
- def as_json options = {}
33
- # Not caching records that don't have IDs.
34
- if !Serializer.configuration.disable_model_caching && self.id && options[:cache_key].present? && !(options.key?(:cache_for) && options[:cache_for].nil?)
35
- cache_key = "#{self.class.name}_____#{options[:cache_key]}___#{self.id}"
36
- if Rails.cache.exist?(cache_key)
37
- Rails.logger.info "Serializer: Cache reading #{cache_key}" if Serializer.configuration.debug
38
- return Rails.cache.read(cache_key)
39
- else
40
- data = super(options)
41
- data = self.class.as_json_associations_alias_fix(options, data)
42
- begin
43
- Rails.logger.info "Serializer: Caching #{cache_key} for #{(options[:cache_for] || Serializer.configuration.default_cache_time)} minutes." if Serializer.configuration.debug
44
- Rails.cache.write(cache_key, data, expires_in: (options[:cache_for] || Serializer.configuration.default_cache_time).minute)
45
- rescue Exception => e
46
- Rails.logger.error "Serializer: Internal Server Error on #{self.class}#as_json ID: #{self.id} for cache key: #{cache_key}"
47
- Rails.logger.error e.class
48
- Rails.logger.error e.message
49
- Rails.logger.error e.backtrace
50
- end
51
- return data
52
- end
53
- else
54
- if Serializer.configuration.debug && !Serializer.configuration.disable_model_caching && self.id && options[:cache_key].present? && options.key?(:cache_for) && options[:cache_for].nil?
55
- Rails.logger.info "Serializer: Caching #{cache_key} NOT caching due to `cache_for: nil`"
56
- end
57
- data = super(options)
58
- data = self.class.as_json_associations_alias_fix(options, data)
59
- return data
60
- end
61
- end
62
-
63
- # Can override the query, using the options. ex: {json_query_override: :tiny_serializer_query}
64
- def serializer opts = {}
65
- query = opts[:json_query_override].present? ? self.class.send(opts[:json_query_override], opts) : self.class.serializer_query(opts)
66
- if Serializer.configuration.enable_includes && query[:include].present? && self.class.column_names.include?('id') && self.id.present? && !opts[:skip_eager_loading] && self.respond_to?(:persisted?) && self.persisted?
67
- # It's an extra SQL call, but most likely worth it to pre-load associations
68
- self.class.includes(self.class.generate_includes_from_json_query(query)).find(self.id).as_json(query)
69
- else
70
- as_json(query)
71
- end
72
- end
73
- # END MODEL INSTANCE METHODS
74
-
75
- class_methods do
76
- # START MODEL CLASS METHODS
77
- def inherited subclass
78
- if subclass.const_defined?("#{subclass.name}Serializer")
79
- serializer_klass = "#{subclass.name}Serializer".constantize
80
-
81
- if serializer_klass.class == Module
82
- if !serializer_klass.const_defined?("SerializerClassAndInstanceMethods")
83
- serializer_klass.const_set('SerializerClassAndInstanceMethods', Module.new {})
84
- end
85
- if !serializer_klass.const_defined?("SerializerClassMethods")
86
- serializer_klass.const_set('SerializerClassMethods', Module.new {})
87
- serializer_klass::SerializerClassMethods.send(:define_method, :get_cumulatively_inherited_serializer_query_list) do |opts = {}|
88
- if defined?(super)
89
- return (subclass::SERIALIZER_QUERY_KEYS_CACHE + superclass.get_cumulatively_inherited_serializer_query_list).uniq
90
- else
91
- return subclass::SERIALIZER_QUERY_KEYS_CACHE
92
- end
93
- end
94
- end
95
-
96
- serializer_query_names = serializer_klass.public_instance_methods
97
-
98
- serializer_query_names.each do |query_name|
99
- serializer_name = query_name[/(?<name>.+)_query/, :name]
100
- if serializer_name.nil?
101
- Rails.logger.info "Serializer: #{serializer_klass.name} method #{query_name} does not end in '(.+)_query', as is expected of serializers" if Serializer.configuration.debug
102
- next
103
- end
104
- # Skip if chosen to override it.
105
- next if serializer_klass.respond_to?(serializer_name)
106
- if serializer_name == 'serializer'
107
- serializer_klass::SerializerClassAndInstanceMethods.send(:define_method, serializer_name) do |opts = {}|
108
- super({json_query_override: query_name}.merge(opts))
109
- end
110
- else
111
- serializer_klass::SerializerClassAndInstanceMethods.send(:define_method, serializer_name) do |opts = {}|
112
- serializer({json_query_override: query_name}.merge(opts))
113
- end
114
- end
115
- end
116
- if serializer_query_names.any?
117
- # Inject instance methods
118
- subclass.send(:include, serializer_klass::SerializerClassAndInstanceMethods)
119
- # Inject class methods
120
- subclass.send(:extend, serializer_klass::SerializerClassAndInstanceMethods)
121
- # Inject class methods that has queries
122
- if Serializer.configuration.debug
123
- Rails.logger.info "Injecting queries: #{serializer_klass.public_instance_methods} into class: #{subclass}"
124
- end
125
- puts "Injecting queries: #{serializer_klass.public_instance_methods} into class: #{subclass}"
126
- subclass.send(:extend, serializer_klass)
127
- # Injecting the Serializer Methods as a namespaced class of the rails class, so we can have
128
- # access to the list of methods to clear their cache.
129
- # 'Class Name + Serializer' does not work with inheritence.
130
- subclass.const_set('SERIALIZER_QUERY_KEYS_CACHE', serializer_query_names)
131
- # Inject class methods
132
- subclass.send(:extend, serializer_klass::SerializerClassMethods)
133
-
134
- # Issue with inheritting classes caching the serializer data from queries in super classes.
135
- # Only on the rails server, not the console strangely.
136
- if DELETE_MATCHED_SUPPORTED_CACHE_TYPES.include?(Rails.configuration.cache_store)
137
- serializer_query_names.each do |query_name|
138
- cache_key_prefix = /#{subclass.name}_____#{query_name}___(\d+)/
139
- puts "Deleting cache here: Rails.cache.delete_matched(#{cache_key_prefix})"
140
- Rails.cache.delete_matched(cache_key_prefix)
141
- end
142
- end
143
- end
144
- else
145
- Rails.logger.info "Serializer: #{serializer_klass.name} was not a Module as expected" if Serializer.configuration.debug
146
- end
147
- end
148
- super(subclass)
149
- end
150
-
151
- # Class defined clear serializer
152
- if DELETE_MATCHED_SUPPORTED_CACHE_TYPES.include?(Rails.configuration.cache_store)
153
- def clear_serializer_cache
154
- self.get_cumulatively_inherited_serializer_query_list.each do |query_name|
155
- cache_key_prefix = /#{self.name}_____#{query_name}___(\d+)/
156
- Rails.logger.info "Serializer: CLEARING CACHE KEY Prefix: #{cache_key_prefix}" if Serializer.configuration.debug
157
- Rails.cache.delete_matched(cache_key_prefix)
158
- end
159
- return true
160
- end
161
- else
162
- def clear_serializer_cache
163
- puts "Not supported by rails cache store: #{Rails.configuration.cache_store}. Supported: #{DELETE_MATCHED_SUPPORTED_CACHE_TYPES}"
164
- return false
165
- end
166
- end
167
-
168
- # Can override the query, using the options. ex: {json_query_override: :tiny_children_serializer_query}
169
- def serializer opts = {}
170
- query = opts[:json_query_override].present? ? self.send(opts[:json_query_override], opts) : serializer_query(opts)
171
- if Serializer.configuration.enable_includes && query[:include].present? && !opts[:skip_eager_loading]
172
- includes(generate_includes_from_json_query(query)).as_json(query)
173
- else
174
- # Have to use 'all' gets stack level too deep otherwise. Not sure why.
175
- all.as_json(query)
176
- end
177
- end
178
-
179
- def as_json_associations_alias_fix options, data, opts = {}
180
- if data
181
- # Depth is almost purely for debugging purposes
182
- opts[:depth] ||= 0
183
- if options[:include].present?
184
- options[:include].each do |include_key, include_hash|
185
- # The includes doesn't have to have a hash attached. Skip it if it doesn't.
186
- next if include_hash.nil?
187
- data_key = include_key.to_s
188
- if include_hash[:as].present?
189
- if include_hash[:as].to_s == include_key.to_s
190
- raise "Serializer: Cannot alias json query association to have the same as the original key; as: #{include_hash[:as].to_s}; original_key: #{include_key.to_s} on self: #{name}"
191
- end
192
- alias_name = include_hash[:as]
193
- data[alias_name.to_s] = data[include_key.to_s]
194
- data.delete(include_key.to_s)
195
- data_key = alias_name.to_s
196
- end
197
- # At this point, the data could be an array of objects, with no as_json options.
198
- if !data[data_key].is_a?(Array)
199
- data[data_key] = as_json_associations_alias_fix(include_hash, data[data_key], {depth: opts[:depth] + 1})
200
- else
201
- data[data_key].each_with_index do |value,i|
202
- data[data_key][i] = as_json_associations_alias_fix(include_hash, value, {depth: opts[:depth] + 1})
203
- end
204
- end
205
- end
206
- end
207
- end
208
- return data
209
- end
210
-
211
- def generate_includes_from_json_query options = {}, klass = nil
212
- query_filter = {}
213
- klass = self if klass.nil?
214
- if options[:include].present? && !options[:skip_eager_loading]
215
- options[:include].each do |include_key, include_hash|
216
- # Will 'next' if there is a scope that takes arguments, an instance-dependent scope.
217
- # Can't eager load when assocation has a instance condition for it's associative scope.
218
- # Might not be a real assocation
219
- next if klass.reflect_on_association(include_key).nil?
220
- next if klass.reflect_on_association(include_key).scope&.arity&.nonzero?
221
- query_filter[include_key] = {}
222
- next if include_hash.none?
223
- query_filter[include_key] = generate_includes_from_json_query(include_hash, klass.reflect_on_association(include_key).klass)
224
- end
225
- end
226
- return query_filter
227
- end
228
- # END MODEL CLASS METHODS
229
-
230
- end
231
- end
232
- end