serega 0.42.0 → 0.51.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.
Files changed (129) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +124 -1207
  3. data/VERSION +1 -1
  4. data/lib/serega/attribute/serializer_reference.rb +27 -0
  5. data/lib/serega/attribute/value_code.rb +63 -0
  6. data/lib/serega/attribute.rb +173 -140
  7. data/lib/serega/attribute_normalizer.rb +236 -391
  8. data/lib/serega/attribute_normalizers/batch.rb +45 -0
  9. data/lib/serega/attribute_normalizers/block.rb +81 -0
  10. data/lib/serega/attribute_normalizers/delegate.rb +34 -0
  11. data/lib/serega/attribute_normalizers/hash_access.rb +37 -0
  12. data/lib/serega/attribute_normalizers/preloads.rb +47 -0
  13. data/lib/serega/attribute_value_resolvers/base.rb +35 -0
  14. data/lib/serega/attribute_value_resolvers/batch.rb +18 -54
  15. data/lib/serega/attribute_value_resolvers/callable.rb +52 -0
  16. data/lib/serega/attribute_value_resolvers/const.rb +12 -24
  17. data/lib/serega/attribute_value_resolvers/delegate.rb +27 -28
  18. data/lib/serega/attribute_value_resolvers/hash_access.rb +49 -52
  19. data/lib/serega/attribute_value_resolvers/keyword.rb +17 -25
  20. data/lib/serega/attribute_values.rb +32 -0
  21. data/lib/serega/batch_loader.rb +37 -0
  22. data/lib/serega/conditions.rb +81 -0
  23. data/lib/serega/config.rb +148 -148
  24. data/lib/serega/engine/pulls.rb +51 -0
  25. data/lib/serega/engine/run.rb +101 -0
  26. data/lib/serega/errors.rb +60 -8
  27. data/lib/serega/formatters/callable.rb +44 -0
  28. data/lib/serega/formatters/method.rb +55 -0
  29. data/lib/serega/formatters.rb +27 -0
  30. data/lib/serega/plan/cache.rb +119 -0
  31. data/lib/serega/plan/depth_limit.rb +36 -0
  32. data/lib/serega/plan/per_ractor_cache.rb +28 -0
  33. data/lib/serega/plan/point.rb +67 -0
  34. data/lib/serega/plan/presets.rb +116 -0
  35. data/lib/serega/plan/selection.rb +94 -0
  36. data/lib/serega/plan/selection_planner.rb +50 -0
  37. data/lib/serega/plan.rb +92 -133
  38. data/lib/serega/plugins/activerecord_preloads/activerecord_preloads.rb +13 -80
  39. data/lib/serega/plugins/activerecord_preloads/lib/preloader.rb +8 -75
  40. data/lib/serega/plugins/context_metadata/context_metadata.rb +40 -123
  41. data/lib/serega/plugins/metadata/check_params.rb +80 -0
  42. data/lib/serega/plugins/metadata/meta_attribute.rb +53 -76
  43. data/lib/serega/plugins/metadata/metadata.rb +38 -175
  44. data/lib/serega/plugins/root/root.rb +94 -235
  45. data/lib/serega/plugins.rb +16 -49
  46. data/lib/serega/presenter.rb +81 -19
  47. data/lib/serega/result_builder.rb +68 -0
  48. data/lib/serega/result_code/attribute_point_code.rb +117 -0
  49. data/lib/serega/result_code/point_code.rb +54 -0
  50. data/lib/serega/result_code/relation_point_code.rb +112 -0
  51. data/lib/serega/result_code.rb +159 -0
  52. data/lib/serega/shareable.rb +52 -0
  53. data/lib/serega/source_group.rb +156 -0
  54. data/lib/serega/utils/camel_case.rb +22 -0
  55. data/lib/serega/utils/collection_detector.rb +20 -13
  56. data/lib/serega/utils/deep_merge.rb +26 -0
  57. data/lib/serega/utils/enum_deep_dup.rb +10 -16
  58. data/lib/serega/utils/enum_deep_freeze.rb +8 -14
  59. data/lib/serega/utils/method_signature.rb +6 -15
  60. data/lib/serega/utils/parse_string_selection.rb +63 -0
  61. data/lib/serega/utils/ractor_local.rb +36 -0
  62. data/lib/serega/utils/ruby_literal.rb +28 -0
  63. data/lib/serega/utils/serialized_attribute_error.rb +60 -20
  64. data/lib/serega/utils/to_hash.rb +5 -26
  65. data/lib/serega/validations/attribute/check_block.rb +3 -15
  66. data/lib/serega/validations/attribute/check_name.rb +4 -15
  67. data/lib/serega/validations/attribute/check_opt_base_serializer.rb +3 -15
  68. data/lib/serega/validations/attribute/check_opt_batch.rb +26 -56
  69. data/lib/serega/validations/attribute/check_opt_condition.rb +55 -0
  70. data/lib/serega/validations/attribute/check_opt_delegate.rb +10 -63
  71. data/lib/serega/validations/attribute/check_opt_format.rb +36 -0
  72. data/lib/serega/validations/attribute/check_opt_hash_access.rb +11 -59
  73. data/lib/serega/validations/attribute/check_opt_hide.rb +3 -14
  74. data/lib/serega/validations/attribute/check_opt_many.rb +18 -20
  75. data/lib/serega/validations/attribute/check_opt_method.rb +3 -25
  76. data/lib/serega/validations/attribute/check_opt_preload.rb +3 -26
  77. data/lib/serega/validations/attribute/check_opt_preset.rb +34 -0
  78. data/lib/serega/validations/attribute/check_opt_selection.rb +41 -0
  79. data/lib/serega/validations/attribute/check_opt_serializer.rb +4 -18
  80. data/lib/serega/validations/attribute/check_opt_value.rb +3 -21
  81. data/lib/serega/validations/check_attribute_params.rb +92 -71
  82. data/lib/serega/validations/check_batch_loader_params.rb +43 -62
  83. data/lib/serega/validations/check_definition_selection.rb +21 -0
  84. data/lib/serega/validations/check_formatter.rb +80 -0
  85. data/lib/serega/validations/check_preset_params.rb +103 -0
  86. data/lib/serega/validations/check_relation_selection.rb +31 -0
  87. data/lib/serega/validations/check_selection.rb +89 -0
  88. data/lib/serega/validations/check_serialize_keywords.rb +23 -0
  89. data/lib/serega/validations/utils/check_allowed_keys.rb +3 -13
  90. data/lib/serega/validations/utils/check_hash_access_value.rb +44 -0
  91. data/lib/serega/validations/utils/check_opt_is_bool.rb +3 -13
  92. data/lib/serega/validations/utils/check_opt_is_hash.rb +3 -13
  93. data/lib/serega/validations/utils/check_opt_is_string_or_symbol.rb +3 -13
  94. data/lib/serega/version.rb +1 -4
  95. data/lib/serega.rb +525 -390
  96. data/sig/serega/plugins.rbs +49 -0
  97. data/sig/serega.rbs +158 -0
  98. metadata +64 -40
  99. data/lib/serega/data_builder.rb +0 -54
  100. data/lib/serega/engine/level.rb +0 -59
  101. data/lib/serega/engine/level_queue.rb +0 -56
  102. data/lib/serega/engine/loader.rb +0 -70
  103. data/lib/serega/helpers/serializer_class_helper.rb +0 -19
  104. data/lib/serega/object_serializer.rb +0 -125
  105. data/lib/serega/plan_point.rb +0 -165
  106. data/lib/serega/plugins/camel_case/camel_case.rb +0 -213
  107. data/lib/serega/plugins/depth_limit/depth_limit.rb +0 -206
  108. data/lib/serega/plugins/explicit_many_option/explicit_many_option.rb +0 -69
  109. data/lib/serega/plugins/explicit_many_option/validations/check_opt_many.rb +0 -38
  110. data/lib/serega/plugins/formatters/formatters.rb +0 -322
  111. data/lib/serega/plugins/if/if.rb +0 -287
  112. data/lib/serega/plugins/if/validations/check_opt_if.rb +0 -72
  113. data/lib/serega/plugins/if/validations/check_opt_if_value.rb +0 -77
  114. data/lib/serega/plugins/if/validations/check_opt_unless.rb +0 -72
  115. data/lib/serega/plugins/if/validations/check_opt_unless_value.rb +0 -77
  116. data/lib/serega/plugins/metadata/validations/check_block.rb +0 -47
  117. data/lib/serega/plugins/metadata/validations/check_opt_const.rb +0 -39
  118. data/lib/serega/plugins/metadata/validations/check_opt_hide_empty.rb +0 -35
  119. data/lib/serega/plugins/metadata/validations/check_opt_hide_nil.rb +0 -35
  120. data/lib/serega/plugins/metadata/validations/check_opt_value.rb +0 -61
  121. data/lib/serega/plugins/metadata/validations/check_opts.rb +0 -59
  122. data/lib/serega/plugins/metadata/validations/check_path.rb +0 -50
  123. data/lib/serega/plugins/string_modifiers/parse_string_modifiers.rb +0 -111
  124. data/lib/serega/plugins/string_modifiers/string_modifiers.rb +0 -63
  125. data/lib/serega/utils/symbol_name.rb +0 -39
  126. data/lib/serega/validations/attribute/check_opt_const.rb +0 -40
  127. data/lib/serega/validations/check_initiate_params.rb +0 -57
  128. data/lib/serega/validations/check_serialize_params.rb +0 -54
  129. data/lib/serega/validations/initiate/check_modifiers.rb +0 -93
data/lib/serega.rb CHANGED
@@ -1,265 +1,370 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "json"
3
4
  require_relative "serega/version"
4
5
 
5
- # Parent class for your serializers
6
+ # Parent class of serializers. A serializer lists attributes and serializes
7
+ # objects to Hashes, JSON, Data or Struct objects:
8
+ #
9
+ # ```ruby
10
+ # class UserSerializer < Serega
11
+ # attribute :first_name
12
+ # attribute :email, hide: true
13
+ # end
14
+ #
15
+ # UserSerializer.to_h(user) # => {first_name: "Bruce"}
16
+ # UserSerializer.to_h(user, with: :email) # => {first_name: "Bruce", email: "bruce@wayne.com"}
17
+ # ```
18
+ #
19
+ # See the [guides](https://github.com/andreyruby/serega/blob/master/docs/README.md).
6
20
  class Serega
7
- # Frozen hash
8
- # @return [Hash] frozen hash
9
- # @private
10
- FROZEN_EMPTY_HASH = {}.freeze
11
-
12
- # Frozen array
13
- # @return [Array] frozen array
14
- # @private
15
- FROZEN_EMPTY_ARRAY = [].freeze
16
-
17
- # Empty modifiers/serialization options (used when serializing with no opts provided)
18
- FROZEN_EMPTY_OPTS = [FROZEN_EMPTY_HASH, nil].freeze
19
- private_constant :FROZEN_EMPTY_OPTS
21
+ # Frozen empty Hash, a shared default in place of a new `{}` per call
22
+ FROZEN_EMPTY_HASH = {}.freeze # :nodoc:
23
+
24
+ # Frozen empty Array, a shared default in place of a new `[]` per call
25
+ FROZEN_EMPTY_ARRAY = [].freeze # :nodoc:
26
+
27
+ # Locks serializers one at a time
28
+ LOCK_MUTEX = Mutex.new # :nodoc:
29
+
30
+ # Errors raised when another Ractor reads a value that is not shareable,
31
+ # empty on a Ruby without Ractors
32
+ # :nocov:
33
+ RACTOR_ISOLATION_ERRORS = (defined?(Ractor) ? [Ractor::IsolationError] : []).freeze # :nodoc:
34
+ # :nocov:
35
+
36
+ # Path prefix of the Serega source files
37
+ LIB_PATH = File.expand_path("serega", __dir__).freeze # :nodoc:
20
38
  end
21
39
 
22
40
  require_relative "serega/errors"
23
- require_relative "serega/helpers/serializer_class_helper"
41
+ require_relative "serega/utils/camel_case"
24
42
  require_relative "serega/utils/collection_detector"
43
+ require_relative "serega/utils/deep_merge"
25
44
  require_relative "serega/utils/enum_deep_dup"
26
45
  require_relative "serega/utils/enum_deep_freeze"
27
46
  require_relative "serega/utils/method_signature"
47
+ require_relative "serega/utils/parse_string_selection"
48
+ require_relative "serega/utils/ractor_local"
49
+ require_relative "serega/utils/ruby_literal"
28
50
  require_relative "serega/utils/serialized_attribute_error"
29
- require_relative "serega/utils/symbol_name"
30
51
  require_relative "serega/utils/to_hash"
52
+ require_relative "serega/attribute_value_resolvers/base"
31
53
  require_relative "serega/attribute_value_resolvers/batch"
54
+ require_relative "serega/attribute_value_resolvers/callable"
32
55
  require_relative "serega/attribute_value_resolvers/const"
33
56
  require_relative "serega/attribute_value_resolvers/delegate"
34
57
  require_relative "serega/attribute_value_resolvers/hash_access"
35
58
  require_relative "serega/attribute_value_resolvers/keyword"
59
+ require_relative "serega/attribute_values"
60
+ require_relative "serega/conditions"
61
+ require_relative "serega/formatters"
62
+ require_relative "serega/formatters/callable"
63
+ require_relative "serega/formatters/method"
36
64
  require_relative "serega/attribute"
65
+ require_relative "serega/attribute/serializer_reference"
66
+ require_relative "serega/attribute/value_code"
67
+ require_relative "serega/attribute_normalizers/batch"
68
+ require_relative "serega/attribute_normalizers/block"
69
+ require_relative "serega/attribute_normalizers/delegate"
70
+ require_relative "serega/attribute_normalizers/hash_access"
71
+ require_relative "serega/attribute_normalizers/preloads"
37
72
  require_relative "serega/attribute_normalizer"
38
- require_relative "serega/engine/level_queue"
39
- require_relative "serega/engine/level"
40
- require_relative "serega/engine/loader"
73
+ require_relative "serega/engine/run"
74
+ require_relative "serega/engine/pulls"
41
75
  require_relative "serega/validations/utils/check_allowed_keys"
76
+ require_relative "serega/validations/utils/check_hash_access_value"
42
77
  require_relative "serega/validations/utils/check_opt_is_bool"
43
78
  require_relative "serega/validations/utils/check_opt_is_hash"
44
79
  require_relative "serega/validations/utils/check_opt_is_string_or_symbol"
45
80
  require_relative "serega/validations/attribute/check_block"
46
81
  require_relative "serega/validations/attribute/check_name"
47
82
  require_relative "serega/validations/attribute/check_opt_base_serializer"
48
- require_relative "serega/validations/attribute/check_opt_const"
83
+ require_relative "serega/validations/attribute/check_opt_condition"
49
84
  require_relative "serega/validations/attribute/check_opt_hide"
50
85
  require_relative "serega/validations/attribute/check_opt_delegate"
86
+ require_relative "serega/validations/attribute/check_opt_format"
51
87
  require_relative "serega/validations/attribute/check_opt_batch"
52
88
  require_relative "serega/validations/attribute/check_opt_hash_access"
53
89
  require_relative "serega/validations/attribute/check_opt_many"
54
90
  require_relative "serega/validations/attribute/check_opt_method"
55
91
  require_relative "serega/validations/attribute/check_opt_preload"
92
+ require_relative "serega/validations/attribute/check_opt_preset"
93
+ require_relative "serega/validations/attribute/check_opt_selection"
56
94
  require_relative "serega/validations/attribute/check_opt_serializer"
57
95
  require_relative "serega/validations/attribute/check_opt_value"
58
- require_relative "serega/validations/initiate/check_modifiers"
96
+ require_relative "serega/validations/check_selection"
97
+ require_relative "serega/validations/check_definition_selection"
98
+ require_relative "serega/validations/check_relation_selection"
59
99
  require_relative "serega/validations/check_attribute_params"
60
- require_relative "serega/validations/check_initiate_params"
61
100
  require_relative "serega/validations/check_batch_loader_params"
62
- require_relative "serega/validations/check_serialize_params"
101
+ require_relative "serega/validations/check_preset_params"
102
+ require_relative "serega/validations/check_formatter"
103
+ require_relative "serega/validations/check_serialize_keywords"
63
104
 
105
+ require_relative "serega/batch_loader"
64
106
  require_relative "serega/config"
65
107
  require_relative "serega/presenter"
66
- require_relative "serega/object_serializer"
67
- require_relative "serega/plan_point"
108
+ require_relative "serega/source_group"
68
109
  require_relative "serega/plan"
69
- require_relative "serega/data_builder"
110
+ require_relative "serega/plan/depth_limit"
111
+ require_relative "serega/plan/point"
112
+ require_relative "serega/plan/selection"
113
+ require_relative "serega/result_code"
114
+ require_relative "serega/result_code/point_code"
115
+ require_relative "serega/result_code/attribute_point_code"
116
+ require_relative "serega/result_code/relation_point_code"
117
+ require_relative "serega/result_builder"
118
+ require_relative "serega/plan/selection_planner"
119
+ require_relative "serega/plan/presets"
120
+ require_relative "serega/plan/cache"
70
121
  require_relative "serega/plugins"
71
122
 
72
123
  class Serega
73
- @config = SeregaConfig.new
74
- @presenter_class = nil
75
-
76
- # Validates `Serializer.attribute` params
77
- check_attribute_params_class = Class.new(SeregaValidations::CheckAttributeParams)
78
- check_attribute_params_class.serializer_class = self
79
- const_set(:CheckAttributeParams, check_attribute_params_class)
80
-
81
- # Validates `Serializer#new` params
82
- check_initiate_params_class = Class.new(SeregaValidations::CheckInitiateParams)
83
- check_initiate_params_class.serializer_class = self
84
- const_set(:CheckInitiateParams, check_initiate_params_class)
85
-
86
- # Validates `serializer#call(obj, PARAMS)` params
87
- check_serialize_params_class = Class.new(SeregaValidations::CheckSerializeParams)
88
- check_serialize_params_class.serializer_class = self
89
- const_set(:CheckSerializeParams, check_serialize_params_class)
90
-
91
- # Validates `Serializer.batch` params
92
- check_batch_loader_params_class = Class.new(SeregaValidations::CheckBatchLoaderParams)
93
- check_batch_loader_params_class.serializer_class = self
94
- const_set(:CheckBatchLoaderParams, check_batch_loader_params_class)
95
-
96
- # Assigns `SeregaEngineLoader` constant to current class
97
- engine_loader_class = Class.new(SeregaEngine::Loader)
98
- engine_loader_class.serializer_class = self
99
- const_set(:SeregaEngineLoader, engine_loader_class)
100
-
101
124
  #
102
- # Serializers class methods
125
+ # Class methods of serializers: they define attributes and serialize
103
126
  #
104
127
  module ClassMethods
105
- # Returns current config
106
- # @return [SeregaConfig] current serializer config
128
+ # Config of the serializer. Subclasses copy it.
129
+ #
130
+ # ```ruby
131
+ # config.hide_by_default = true
132
+ # ```
133
+ #
134
+ # See [Configuration](https://github.com/andreyruby/serega/blob/master/docs/configuration.md).
107
135
  attr_reader :config
136
+
108
137
  #
109
- # Enables plugin for current serializer
138
+ # Turns on a built-in feature by name, with its options. Subclasses get it
139
+ # too.
110
140
  #
111
- # @param name [Symbol, Class<Module>] Plugin name or plugin module itself
112
- # @param opts [Hash>] Plugin options
141
+ # ```ruby
142
+ # plugin :root, root_one: :user, root_many: :users
143
+ # ```
113
144
  #
114
- # @return [class<Module>] Loaded plugin module
145
+ # See [Root Key and Metadata](https://github.com/andreyruby/serega/blob/master/docs/root-and-metadata.md).
115
146
  #
116
147
  def plugin(name, **opts)
148
+ check_unlocked
117
149
  raise SeregaError, "This plugin is already loaded" if plugin_used?(name)
118
150
 
119
- plugin = SeregaPlugins.find_plugin(name)
120
-
121
- # We split loading of plugin to three parts - before_load, load, after_load:
122
- #
123
- # - **before_load_plugin** usually used to check requirements and to load additional plugins
124
- # - **load_plugin** usually used to include plugin modules
125
- # - **after_load_plugin** usually used to add config options
126
- plugin.before_load_plugin(self, **opts) if plugin.respond_to?(:before_load_plugin)
127
- plugin.load_plugin(self, **opts) if plugin.respond_to?(:load_plugin)
128
- plugin.after_load_plugin(self, **opts) if plugin.respond_to?(:after_load_plugin)
129
-
130
- # Store attached plugins, so we can check it is loaded later
131
- config.plugins << (plugin.respond_to?(:plugin_name) ? plugin.plugin_name : plugin)
151
+ plugin = SeregaPlugins.find(name)
152
+ plugin.apply(self, **opts)
153
+ config.plugins << name
132
154
 
133
155
  plugin
134
156
  end
135
157
 
136
- #
137
158
  # Checks plugin is used
138
- #
139
- # @param name [Symbol, Class<Module>] Plugin name or plugin module itself
140
- #
141
- # @return [Boolean] Is plugin used
142
- #
143
- # @private
144
- def plugin_used?(name)
145
- plugin_name =
146
- case name
147
- when Module then name.respond_to?(:plugin_name) ? name.plugin_name : name
148
- else name
149
- end
150
-
151
- config.plugins.include?(plugin_name)
159
+ def plugin_used?(name) # :nodoc:
160
+ config.plugins.include?(name)
152
161
  end
153
162
 
154
163
  #
155
- # Lists attributes
164
+ # Attributes by name, hidden and inherited ones too
156
165
  #
157
- # @return [Hash] attributes list
166
+ # ```ruby
167
+ # UserSerializer.attributes.keys # => [:first_name, :email]
168
+ # ```
158
169
  #
159
- # @private
160
170
  def attributes
161
- @attributes ||= {}
171
+ @attributes
162
172
  end
163
173
 
164
174
  #
165
- # Lists defined batch loaders
175
+ # Presets by name: the names of the presets each one includes and its
176
+ # own field selection
166
177
  #
167
- # @return [Hash] batch loaders list
178
+ # ```ruby
179
+ # UserSerializer.presets # => {card: {presets: [], only: {posts: {title: {}}}, with: {}, except: {}}}
180
+ # ```
168
181
  #
169
- # @private
170
- def batch_loaders
171
- @batch_loaders ||= {}
182
+ def presets
183
+ @presets
184
+ end
185
+
186
+ # Lists defined batch loaders
187
+ def batch_loaders # :nodoc:
188
+ @batch_loaders
189
+ end
190
+
191
+ # Lists defined formatters
192
+ def formatters # :nodoc:
193
+ @formatters
194
+ end
195
+
196
+ # Cached serialization plans
197
+ def plan_cache # :nodoc:
198
+ @plan_cache
199
+ # :nocov:
200
+ rescue *RACTOR_ISOLATION_ERRORS
201
+ raise SeregaError, @unshareable_reason if @unshareable_reason
202
+
203
+ raise SeregaError, "#{self} can not serialize in other Ractors. Call `make_shareable!` at the end of its definition"
204
+ # :nocov:
205
+ end
206
+
207
+ # Returns the presenter class that wraps objects in the current Ractor,
208
+ # `nil` without presenter methods. A shareable serializer gives each
209
+ # Ractor its own subclass of the presenter, which defines delegators
210
+ # in its own `Delegators` module.
211
+ def local_presenter # :nodoc:
212
+ key = @presenter_key
213
+ return @presenter_class unless key
214
+
215
+ SeregaUtils::RactorLocal.fetch(key) { Class.new(@presenter_class) }
172
216
  end
173
217
 
174
- #
175
218
  # Lists blocks given to `presenter`, in definition order
176
- #
177
- # @return [Array<Proc>] presenter blocks list
178
- #
179
- # @private
180
- def presenter_blocks
181
- @presenter_blocks ||= []
219
+ def presenter_blocks # :nodoc:
220
+ @presenter_blocks
221
+ end
222
+
223
+ # Returns (and caches) the Data class of the serialized objects with the
224
+ # given members
225
+ def data_class_for(point_names) # :nodoc:
226
+ classes = @data_classes
227
+ classes = SeregaUtils::RactorLocal.fetch(SeregaUtils::RactorLocal.key(self, :data_classes)) { {} } if classes.frozen?
228
+ classes[point_names] ||= Data.define(*point_names)
229
+ end
230
+
231
+ # Returns (and caches) the Struct class of the serialized objects with
232
+ # the given members
233
+ def struct_class_for(point_names) # :nodoc:
234
+ classes = @struct_classes
235
+ classes = SeregaUtils::RactorLocal.fetch(SeregaUtils::RactorLocal.key(self, :struct_classes)) { {} } if classes.frozen?
236
+ classes[point_names] ||= Struct.new(*point_names)
182
237
  end
183
238
 
184
239
  #
185
- # Adds attribute
240
+ # Adds an attribute. By default its value is `object.<name>`, and the
241
+ # options change that:
186
242
  #
187
- # @param name [Symbol] Attribute name. Attribute value will be found by executing `object.<name>`
188
- # @param opts [Hash] Options to serialize attribute
189
- # @param block [Proc] Defines attributes of a nested anonymous serializer.
190
- # The block is executed in the context of that serializer, so everything
191
- # available in a serializer class body can be used inside. The attribute
192
- # value (found by name/:method/:value/:delegate/:const/:batch as usual)
193
- # is serialized with this nested serializer. The nested serializer
194
- # inherits from the `:base_serializer` attribute option or
195
- # `config.base_serializer` (one of them is required).
243
+ # ```ruby
244
+ # attribute :first_name
245
+ # attribute :name, method: :full_name
246
+ # attribute :email, hide: true
247
+ # attribute :posts, serializer: PostSerializer
248
+ # attribute :posts, serializer: PostSerializer, preset: :summary # fields of a preset
249
+ # attribute :posts, serializer: PostSerializer, only: [:id, :title]
250
+ # ```
196
251
  #
197
- # @example
198
- # attribute :statistics, method: :itself do
199
- # attribute :likes_count
200
- # attribute :comments_count
201
- # end
252
+ # A block defines the attributes of a nested serializer. It inherits from
253
+ # the `:base_serializer` option or `config.base_serializer`:
202
254
  #
203
- # @return [Serega::SeregaAttribute] Added attribute
255
+ # ```ruby
256
+ # attribute :statistics, method: :itself do
257
+ # attribute :likes_count
258
+ # attribute :comments_count
259
+ # end
260
+ # ```
261
+ #
262
+ # See [Attributes](https://github.com/andreyruby/serega/blob/master/docs/attributes.md#all-options)
263
+ # for all options.
204
264
  #
205
265
  def attribute(name, **opts, &block)
206
- attribute = self::SeregaAttribute.new(name: name, opts: opts, block: block)
266
+ check_unlocked
267
+ location = caller_locations.find { |caller_location| !caller_location.path.start_with?(LIB_PATH) }
268
+ attribute = SeregaAttribute.new(self, name: name, opts: opts, block: block, location: location && "#{location.path}:#{location.lineno}")
207
269
  attributes[attribute.name] = attribute
208
270
  end
209
271
 
210
272
  #
211
- # Defines a batch loader
273
+ # Saves the `only`, `with` and `except` options under a name. The
274
+ # `preset:` serialization option selects the fields of the presets,
275
+ # merged with the options given in the call. A preset replaces the preset with the same
276
+ # name.
212
277
  #
213
- # @example
214
- # batch :tags, PostTagsLoader
278
+ # - `preset:` names presets defined earlier. They are merged when the
279
+ # preset is used, thus a redefined preset changes the presets that
280
+ # include it.
215
281
  #
216
- # @example with block
217
- # batch_loader(:tags) do |posts|
218
- # Tags.where(post: posts).group(:post_id).pluck(:post_id, Arel.sql('ARRAY_AGG(tags.tag ORDER BY tag)')).to_h
219
- # end
282
+ # ```ruby
283
+ # preset :card, only: [:first_name, {avatar: :url}]
284
+ # preset :profile, preset: :card, with: {posts: :comments}
220
285
  #
221
- # attribute :tags, batch: :tags, value: { |post, batch:| batch[:tags][post.id] }
286
+ # UserSerializer.to_h(user, preset: :profile, except: :avatar)
287
+ # ```
222
288
  #
223
- # @example with context
224
- # batch_loader(:tags) do |posts, ctx:|
225
- # next {} if ctx[:bot]
289
+ # See [Presets](https://github.com/andreyruby/serega/blob/master/docs/selecting-fields.md#presets).
226
290
  #
227
- # Tags.where(post: posts).group(:post_id).pluck(:post_id, Arel.sql('ARRAY_AGG(tags.tag ORDER BY tag)')).to_h
228
- # end
291
+ def preset(name, preset: nil, only: nil, with: nil, except: nil)
292
+ check_unlocked
293
+ definition = SeregaPlan::Presets.define(self, name, preset, only, with, except)
294
+ presets[name.to_sym] = definition
295
+ end
296
+
229
297
  #
230
- # attribute :tags, batch: :tags, value: { |post, batch:| batch[:tags][post.id] }
298
+ # Defines a named batch loader: a callable or a block that receives the
299
+ # objects, and the context as a second parameter or as the `:ctx`
300
+ # keyword. It returns the values by object id. Subclasses inherit it.
231
301
  #
232
- # @param name [Symbol] A batch loader name
233
- # @param value [#call] Batch loader
234
- # @param block [Proc] Batch loader
302
+ # ```ruby
303
+ # batch :likes_count, ->(users) { Like.where(user: users).group(:user_id).count }
304
+ # batch(:rank) { |users, ctx:| Rank.for(users, ctx[:season]) }
235
305
  #
236
- # @return [#call] Batch loader
306
+ # attribute :likes_count, batch: true
307
+ # ```
308
+ #
309
+ # See [Batch loading](https://github.com/andreyruby/serega/blob/master/docs/batch-loading.md).
237
310
  #
238
311
  def batch(name, value = nil, &block)
239
- raise SeregaError, "Batch loader must be defined with a callable value or block" if (value && block) || (!value && !block)
312
+ check_unlocked
313
+ raise SeregaError, "Batch loader must be defined with a callable value or block" if !value == !block
240
314
 
241
- batch_loader = self::SeregaEngineLoader.new(name: name, block: value || block)
315
+ batch_loader = SeregaBatchLoader.new(name: name, block: value || block)
242
316
  batch_loaders[batch_loader.name] = batch_loader
243
317
  end
244
318
 
245
319
  #
246
- # Defines presenter methods — evaluates the block inside the serializer's own
247
- # presenter class. Multiple blocks accumulate.
320
+ # Defines a named formatter for the `:format` attribute option. A formatter
321
+ # is a method name called on the value, an Array of a method name and its
322
+ # arguments, or a callable or a block that receives the value, and the
323
+ # context as a second parameter or as the `:ctx` keyword. With
324
+ # `allow_nil: true` a `nil` value stays `nil`. Subclasses inherit it.
248
325
  #
249
- # presenter do
250
- # def name
251
- # [first_name, last_name].compact.join(" ")
252
- # end
253
- # end
326
+ # ```ruby
327
+ # formatter :string, :to_s
328
+ # formatter :iso8601, [:iso8601, 3]
329
+ # formatter(:money) { |cents, ctx| "#{cents / 100.0} #{ctx[:currency]}" }
254
330
  #
255
- # @param block [Proc] Presenter methods
331
+ # attribute :created_at, format: :iso8601
332
+ # ```
333
+ #
334
+ # See [Formatters](https://github.com/andreyruby/serega/blob/master/docs/formatters.md).
335
+ #
336
+ def formatter(name, value = nil, allow_nil: false, &block)
337
+ check_unlocked
338
+ raise SeregaError, "Formatter name must be a Symbol" unless name.is_a?(Symbol)
339
+ raise SeregaError, "Formatter must be defined with a value or a block" if !value == !block
340
+ raise SeregaError, "Invalid option :allow_nil => #{allow_nil.inspect}. Must have a boolean value" unless allow_nil == true || allow_nil == false
341
+
342
+ value ||= block
343
+ SeregaValidations::CheckFormatter.call(name, value)
344
+ formatters[name] = SeregaFormatters.build({use: value, allow_nil: allow_nil})
345
+ end
346
+
256
347
  #
257
- # @return [Class<SeregaPresenter>, nil] the serializer presenter class,
258
- # nil when the serializer has none
348
+ # Defines presenter methods: attributes read their values from them. The
349
+ # block runs in the presenter class of the serializer, and each call adds
350
+ # methods. Returns the presenter class, `nil` without one.
351
+ #
352
+ # ```ruby
353
+ # attribute :name
354
+ #
355
+ # presenter do
356
+ # def name
357
+ # [first_name, last_name].compact.join(" ")
358
+ # end
359
+ # end
360
+ # ```
361
+ #
362
+ # See [Presenter](https://github.com/andreyruby/serega/blob/master/docs/presenter.md).
259
363
  #
260
364
  def presenter(&block)
261
365
  return @presenter_class unless block
262
366
 
367
+ check_unlocked
263
368
  @presenter_class ||= Class.new(SeregaPresenter)
264
369
  @presenter_class.class_exec(&block)
265
370
  presenter_blocks << block
@@ -267,31 +372,23 @@ class Serega
267
372
  end
268
373
 
269
374
  #
270
- # Registers (or returns) the handler used to preload an attribute's
271
- # associations onto the records gathered during serialization.
272
- #
273
- # The handler is called once per preloaded attribute with the gathered
274
- # objects and that attribute's preloads. ORM plugins register a handler
275
- # that performs the actual eager loading.
375
+ # Sets the handler that preloads the `:preload` value of an attribute. It
376
+ # runs once per attribute with a preload, with the objects to serialize
377
+ # and the preloads. Without arguments, returns the handler. Subclasses
378
+ # inherit it.
276
379
  #
277
- # @example with a block
278
- # preload_with { |objects, preloads| MyORM.eager_load(objects, preloads) }
380
+ # ```ruby
381
+ # preload_with { |objects, preloads| RecordPreloader.call(objects, preloads) }
382
+ # preload_with AppPreloader
383
+ # ```
279
384
  #
280
- # @example with a callable value
281
- # preload_with MyPreloader
282
- #
283
- # @param value [#call, nil] Preload handler accepting two positional arguments
284
- # @param block [Proc] Preload handler accepting two positional arguments
285
- #
286
- # @return [#call, nil] The registered preload handler
385
+ # See [Preloads](https://github.com/andreyruby/serega/blob/master/docs/preloads.md).
287
386
  #
288
387
  def preload_with(value = nil, &block)
289
388
  return @preload_with if value.nil? && block.nil?
290
- raise SeregaError, "preload_with accepts a single callable or a block, not both" if value && block
291
-
292
- handler = value || block
293
- raise SeregaError, "preload_with value must be a Proc or respond to #call" if !handler.is_a?(Proc) && !handler.respond_to?(:call)
294
389
 
390
+ check_unlocked
391
+ handler = checked_handler(:preload_with, value, block)
295
392
  signature = SeregaUtils::MethodSignature.call(handler, pos_limit: 2)
296
393
  raise SeregaError, "preload_with handler must accept two positional arguments: (objects, preloads)" unless signature == "2"
297
394
 
@@ -299,45 +396,25 @@ class Serega
299
396
  end
300
397
 
301
398
  #
302
- # Registers (or returns) the handler that replaces the serialized objects
303
- # before serialization starts.
399
+ # Sets the handler that replaces the objects given to the serializer, for
400
+ # example ids with records. It runs once per serialization, before Serega
401
+ # detects a list, and receives the objects, and the context as a second
402
+ # parameter or as the `:ctx` keyword. Objects of relations skip it.
403
+ # Without arguments, returns the handler.
304
404
  #
305
- # The handler is called once per serialization with the objects provided to
306
- # `.call`/`.to_h`/`.to_data` and the serialization context. Its result is
307
- # serialized instead of the provided objects, which allows to accept ids or
308
- # other references and load the records in one place.
405
+ # ```ruby
406
+ # prepare_initial_objects { |user_ids| User.where(id: user_ids) }
407
+ # prepare_initial_objects { |ids, ctx:| User.where(id: ids, account: ctx[:account]) }
408
+ # prepare_initial_objects UsersLoader
409
+ # ```
309
410
  #
310
- # The handler runs before the `:many` option is detected, so it may turn a
311
- # single object into a collection and back. A provided `:many` serialization
312
- # option is still used as is.
313
- #
314
- # The handler runs only for the serialized objects, and not for objects of
315
- # nested serializers.
316
- #
317
- # @example with a block
318
- # prepare_initial_objects { |user_ids| User.where(id: user_ids) }
319
- #
320
- # @example with a context
321
- # prepare_initial_objects { |user_ids, ctx| User.where(id: user_ids, account: ctx[:account]) }
322
- #
323
- # @example with a keyword context
324
- # prepare_initial_objects { |user_ids, ctx:| User.where(id: user_ids, account: ctx[:account]) }
325
- #
326
- # @example with a callable value
327
- # prepare_initial_objects UsersLoader
328
- #
329
- # @param value [#call, nil] Handler accepting (objects), (objects, context) or (objects, ctx:)
330
- # @param block [Proc] Handler accepting (objects), (objects, context) or (objects, ctx:)
331
- #
332
- # @return [#call, nil] The registered handler
411
+ # See [Prepare initial objects](https://github.com/andreyruby/serega/blob/master/docs/prepare-initial-objects.md).
333
412
  #
334
413
  def prepare_initial_objects(value = nil, &block)
335
414
  return @prepare_initial_objects if value.nil? && block.nil?
336
- raise SeregaError, "prepare_initial_objects accepts a single callable or a block, not both" if value && block
337
-
338
- handler = value || block
339
- raise SeregaError, "prepare_initial_objects value must be a Proc or respond to #call" if !handler.is_a?(Proc) && !handler.respond_to?(:call)
340
415
 
416
+ check_unlocked
417
+ handler = checked_handler(:prepare_initial_objects, value, block)
341
418
  signature = SeregaUtils::MethodSignature.call(handler, pos_limit: 2, keyword_args: [:ctx])
342
419
  raise SeregaError, prepare_initial_objects_signature_error unless %w[1 2 1_ctx].include?(signature)
343
420
 
@@ -345,132 +422,183 @@ class Serega
345
422
  @prepare_initial_objects = handler
346
423
  end
347
424
 
348
- #
349
425
  # Signature of the registered prepare_initial_objects handler
350
- #
351
- # @return [String, nil] Handler signature
352
- #
353
- # @private
354
- def prepare_initial_objects_signature
355
- @prepare_initial_objects_signature
356
- end
426
+ attr_reader :prepare_initial_objects_signature # :nodoc:
427
+
428
+ # Patched in:
429
+ # - plugin :root (takes the options of plugins)
357
430
 
358
431
  #
359
- # Serializes provided object to Hash
432
+ # Serializes an object or a list to a Hash or an Array of Hashes. `nil`
433
+ # serializes to `nil`.
360
434
  #
361
- # @param object [Object] Serialized object
362
- # @param opts [Hash, nil] Serializer modifiers and other instantiating options
363
- # @option opts [Array, Hash, String, Symbol] :only The only attributes to serialize
364
- # @option opts [Array, Hash, String, Symbol] :except Attributes to hide
365
- # @option opts [Array, Hash, String, Symbol] :with Attributes (usually hidden) to serialize additionally
366
- # @option opts [Boolean] :validate Validates provided modifiers (Default is true)
367
- # @option opts [Hash] :context Serialization context
368
- # @option opts [Boolean] :many Set true if provided multiple objects (Default `object.is_a?(Enumerable) && !object.is_a?(Hash) && !object.is_a?(Struct)`)
435
+ # - `only`, `except`, `with`: fields to serialize, to skip and to add,
436
+ # see [Selecting fields](https://github.com/andreyruby/serega/blob/master/docs/selecting-fields.md);
437
+ # - `check_selection`: `false` skips unknown fields, by default
438
+ # `config.check_selection`;
439
+ # - `context`: data for attribute values and conditions;
440
+ # - `many`: `true` serializes a list, `false` one object. By default an
441
+ # `Enumerable` that is not a `Hash` or `Struct` is a list.
369
442
  #
370
- # @return [Hash] Serialization result
443
+ # ```ruby
444
+ # UserSerializer.to_h(user) # => {first_name: "Bruce"}
445
+ # UserSerializer.to_h([user], with: :email) # => [{first_name: "Bruce", email: "bruce@wayne.com"}]
446
+ # UserSerializer.to_h(user, context: {admin: true})
447
+ # ```
371
448
  #
372
- def call(object, opts = nil)
373
- opts = opts&.transform_keys(&:to_sym)
374
- modifiers_opts = init_modifier_opts(opts)
375
- serialize_opts = init_serialize_opts(opts)
376
- new(modifiers_opts).to_h(object, serialize_opts)
449
+ # See [Serializing](https://github.com/andreyruby/serega/blob/master/docs/serializing.md).
450
+ #
451
+ def call(object, only: nil, with: nil, except: nil, preset: nil, check_selection: nil, context: nil, many: nil)
452
+ # The serialization methods list each keyword instead of taking
453
+ # `**opts`: a `**opts` Hash allocates on every call, even when empty.
454
+ new(only: only, with: with, except: except, preset: preset, check_selection: check_selection)
455
+ .to_h(object, context: context, many: many)
377
456
  end
378
457
 
458
+ # Patched in:
459
+ # - plugin :root (takes the options of plugins)
460
+
379
461
  #
380
- # Serializes provided object to a tree of Ruby Data objects
381
- #
382
- # @param object [Object] Serialized object
383
- # @param opts [Hash, nil] Serializer modifiers and other instantiating options
384
- # @option opts [Array, Hash, String, Symbol] :only The only attributes to serialize
385
- # @option opts [Array, Hash, String, Symbol] :except Attributes to hide
386
- # @option opts [Array, Hash, String, Symbol] :with Attributes (usually hidden) to serialize additionally
387
- # @option opts [Boolean] :validate Validates provided modifiers (Default is true)
388
- # @option opts [Hash] :context Serialization context
389
- # @option opts [Boolean] :many Set true if provided multiple objects (Default `object.is_a?(Enumerable) && !object.is_a?(Hash) && !object.is_a?(Struct)`)
462
+ # Serializes like #to_h, to `Data` objects
390
463
  #
391
- # @return [Data, Array<Data>, nil] Serialization result as Data object(s)
464
+ # ```ruby
465
+ # UserSerializer.to_data(user) # => #<data first_name="Bruce">
466
+ # ```
392
467
  #
393
- def to_data(object, opts = nil)
394
- opts = opts&.transform_keys(&:to_sym)
395
- modifiers_opts = init_modifier_opts(opts)
396
- serialize_opts = init_serialize_opts(opts)
397
- new(modifiers_opts).to_data(object, serialize_opts)
468
+ def to_data(object, only: nil, with: nil, except: nil, preset: nil, check_selection: nil, context: nil, many: nil)
469
+ new(only: only, with: with, except: except, preset: preset, check_selection: check_selection)
470
+ .to_data(object, context: context, many: many)
398
471
  end
399
472
 
400
- alias_method :to_h, :call
401
-
402
- private
403
-
404
- def init_modifier_opts(opts)
405
- (!opts || opts.empty?) ? FROZEN_EMPTY_HASH : opts.slice(*config.initiate_keys)
406
- end
473
+ # Patched in:
474
+ # - plugin :root (takes the options of plugins)
407
475
 
408
- def init_serialize_opts(opts)
409
- (!opts || opts.empty?) ? nil : opts.except(*config.initiate_keys)
476
+ #
477
+ # Serializes like #to_h, to `Struct` objects
478
+ #
479
+ # ```ruby
480
+ # UserSerializer.to_struct(user) # => #<struct first_name="Bruce">
481
+ # ```
482
+ #
483
+ def to_struct(object, only: nil, with: nil, except: nil, preset: nil, check_selection: nil, context: nil, many: nil)
484
+ new(only: only, with: with, except: except, preset: preset, check_selection: check_selection)
485
+ .to_struct(object, context: context, many: many)
410
486
  end
411
487
 
412
488
  # Patched in:
413
- # - plugin :metadata (defines MetaAttribute and copies meta_attributes to subclasses)
414
- def inherited(subclass)
415
- config_class = Class.new(self::SeregaConfig)
416
- config_class.serializer_class = subclass
417
- subclass.const_set(:SeregaConfig, config_class)
418
- subclass.instance_variable_set(:@config, subclass::SeregaConfig.new(config.opts))
489
+ # - plugin :root (takes the options of plugins)
419
490
 
420
- attribute_class = Class.new(self::SeregaAttribute)
421
- attribute_class.serializer_class = subclass
422
- subclass.const_set(:SeregaAttribute, attribute_class)
491
+ #
492
+ # Serializes like #to_h, to a JSON String: `JSON.generate` of the #to_h
493
+ # result
494
+ #
495
+ # ```ruby
496
+ # UserSerializer.to_json(user) # => "{\"first_name\":\"Bruce\"}"
497
+ # ```
498
+ #
499
+ def to_json(object, only: nil, with: nil, except: nil, preset: nil, check_selection: nil, context: nil, many: nil)
500
+ new(only: only, with: with, except: except, preset: preset, check_selection: check_selection)
501
+ .to_json(object, context: context, many: many)
502
+ end
423
503
 
424
- attribute_normalizer_class = Class.new(self::SeregaAttributeNormalizer)
425
- attribute_normalizer_class.serializer_class = subclass
426
- subclass.const_set(:SeregaAttributeNormalizer, attribute_normalizer_class)
504
+ alias_method :to_h, :call
427
505
 
428
- data_builder_class = Class.new(self::SeregaDataBuilder)
429
- data_builder_class.serializer_class = subclass
430
- subclass.const_set(:SeregaDataBuilder, data_builder_class)
506
+ # Locks serializer definitions and config from changes.
507
+ # Called when a serialization plan is built for the serializer.
508
+ def lock # :nodoc:
509
+ return if @locked
431
510
 
432
- plan_class = Class.new(self::SeregaPlan)
433
- plan_class.serializer_class = subclass
434
- subclass.const_set(:SeregaPlan, plan_class)
511
+ LOCK_MUTEX.synchronize do
512
+ next if @locked
513
+
514
+ SeregaUtils::EnumDeepFreeze.call(config.opts)
515
+ if @presenter_class
516
+ define_presenter_delegators
517
+ attributes.each_value { |attribute| attribute.check_presenter(@presenter_class) }
518
+ end
519
+ @locked = true
520
+ end
521
+ end
435
522
 
436
- plan_point_class = Class.new(self::SeregaPlanPoint)
437
- plan_point_class.serializer_class = subclass
438
- subclass.const_set(:SeregaPlanPoint, plan_point_class)
523
+ #
524
+ # Makes the serializer shareable between Ractors. Call it at the end of a
525
+ # definition to serialize in other Ractors. It locks the serializer and
526
+ # its nested serializers defined with blocks. A serializer with a
527
+ # definition that can not be shared serializes in the main Ractor only.
528
+ #
529
+ # ```ruby
530
+ # class UserSerializer < Serega
531
+ # attribute :first_name
532
+ #
533
+ # make_shareable!
534
+ # end
535
+ # ```
536
+ #
537
+ # See [Ractors](https://github.com/andreyruby/serega/blob/master/docs/ractors.md).
538
+ #
539
+ def make_shareable!
540
+ return self if @shareable
541
+
542
+ lock
543
+ attributes.each_value { |attribute| attribute.serializer.make_shareable! if attribute.initials[:block] }
544
+ @shareable = true
545
+ # :nocov:
546
+ if defined?(Ractor)
547
+ require_relative "serega/shareable"
548
+ require_relative "serega/plan/per_ractor_cache"
549
+ # Other Ractors can not define methods in the presenter, thus each
550
+ # Ractor wraps objects in its own subclass of it
551
+ if @presenter_class
552
+ @presenter_class::Delegators.freeze
553
+ @presenter_key = SeregaUtils::RactorLocal.key(self, :presenter)
554
+ end
555
+ @unshareable_reason = SeregaShareable.call(self)
556
+ @plan_cache = SeregaPlan::PerRactorCache.new(self, SeregaPlan::SelectionPlanner) unless @unshareable_reason
557
+ end
558
+ # :nocov:
559
+ self
560
+ end
439
561
 
440
- engine_loader_class = Class.new(self::SeregaEngineLoader)
441
- engine_loader_class.serializer_class = subclass
442
- subclass.const_set(:SeregaEngineLoader, engine_loader_class)
562
+ # Shows whether `make_shareable!` was called
563
+ def shareable? # :nodoc:
564
+ @shareable
565
+ end
443
566
 
444
- object_serializer_class = Class.new(self::SeregaObjectSerializer)
445
- object_serializer_class.serializer_class = subclass
446
- subclass.const_set(:SeregaObjectSerializer, object_serializer_class)
567
+ private
447
568
 
448
- check_attribute_params_class = Class.new(self::CheckAttributeParams)
449
- check_attribute_params_class.serializer_class = subclass
450
- subclass.const_set(:CheckAttributeParams, check_attribute_params_class)
569
+ # Defines the presenter delegators of the attributes that read a method of
570
+ # the object. Later reads skip method_missing, also in other Ractors,
571
+ # which can not define methods in classes of the main Ractor.
572
+ def define_presenter_delegators
573
+ object_methods = attributes.each_value.filter_map(&:object_method)
574
+ @presenter_class.define_delegators(object_methods)
575
+ end
451
576
 
452
- check_initiate_params_class = Class.new(self::CheckInitiateParams)
453
- check_initiate_params_class.serializer_class = subclass
454
- subclass.const_set(:CheckInitiateParams, check_initiate_params_class)
577
+ def check_unlocked
578
+ raise SeregaError, "#{self} can not be changed after it was made shareable" if @shareable
579
+ raise SeregaError, "#{self} can not be changed after it was used for serialization" if @locked
580
+ end
455
581
 
456
- check_serialize_params_class = Class.new(self::CheckSerializeParams)
457
- check_serialize_params_class.serializer_class = subclass
458
- subclass.const_set(:CheckSerializeParams, check_serialize_params_class)
582
+ # Patched in:
583
+ # - plugin :metadata (copies meta_attributes to subclasses)
584
+ def inherited(subclass)
585
+ subclass.const_set(:SeregaConfig, Class.new(self::SeregaConfig))
586
+ subclass.const_set(:SeregaAttributeValues, Class.new(self::SeregaAttributeValues))
587
+ subclass.send(:initialize_definition, subclass::SeregaConfig.new(config.opts), formatters.dup)
459
588
 
460
- check_batch_loader_params_class = Class.new(self::CheckBatchLoaderParams)
461
- check_batch_loader_params_class.serializer_class = self
462
- subclass.const_set(:CheckBatchLoaderParams, check_batch_loader_params_class)
589
+ # Assign same batch loaders before the attributes that use them
590
+ batch_loaders.each_value do |loader|
591
+ subclass.batch(loader.name, loader.block)
592
+ end
463
593
 
464
594
  # Assign same attributes
465
595
  attributes.each_value do |attr|
466
- params = attr.initials
467
- subclass.attribute(params[:name], **params[:opts], &params[:block])
596
+ subclass_attribute = SeregaAttribute.new(subclass, **attr.initials)
597
+ subclass.attributes[subclass_attribute.name] = subclass_attribute
468
598
  end
469
599
 
470
- # Assign same batch loaders
471
- batch_loaders.each_value do |loader|
472
- subclass.batch(loader.name, loader.block)
473
- end
600
+ # Assign same presets
601
+ subclass.presets.merge!(presets)
474
602
 
475
603
  # Assign same preload handler
476
604
  subclass.preload_with(preload_with) if preload_with
@@ -486,6 +614,39 @@ class Serega
486
614
  super
487
615
  end
488
616
 
617
+ # Starts the definition of a serializer class with its config and the
618
+ # formatters it inherits. Serega and each subclass set the same instance
619
+ # variables in the same order.
620
+ def initialize_definition(config, formatters)
621
+ @config = config
622
+ @attributes = {}
623
+ @presets = {}
624
+ @batch_loaders = {}
625
+ @formatters = formatters
626
+ @presenter_class = nil
627
+ @presenter_blocks = []
628
+ @presenter_key = nil
629
+ @data_classes = {}
630
+ @struct_classes = {}
631
+ @preload_with = nil
632
+ @prepare_initial_objects = nil
633
+ @prepare_initial_objects_signature = nil
634
+ @locked = false
635
+ @shareable = false
636
+ @unshareable_reason = nil
637
+ @plan_cache = SeregaPlan::Cache.new(self, SeregaPlan::SelectionPlanner)
638
+ end
639
+
640
+ # The handler given to `method_name` as a value or a block
641
+ def checked_handler(method_name, value, block)
642
+ raise SeregaError, "#{method_name} accepts a single callable or a block, not both" if value && block
643
+
644
+ handler = value || block
645
+ raise SeregaError, "#{method_name} value must be a Proc or respond to #call" unless handler.respond_to?(:call)
646
+
647
+ handler
648
+ end
649
+
489
650
  def prepare_initial_objects_signature_error
490
651
  <<~ERR.strip
491
652
  prepare_initial_objects handler arguments should have one of this signatures:
@@ -497,118 +658,99 @@ class Serega
497
658
  end
498
659
 
499
660
  #
500
- # Serializers instance methods
661
+ # Instance methods of serializers. An instance keeps its field selection
662
+ # and serializes many times.
501
663
  #
502
664
  module InstanceMethods
503
665
  #
504
- # Instantiates new Serega class
505
- #
506
- # @param opts [Hash, nil] Serializer modifiers and other instantiating options
507
- # @option opts [Array, Hash, String, Symbol] :only The only attributes to serialize
508
- # @option opts [Array, Hash, String, Symbol] :except Attributes to hide
509
- # @option opts [Array, Hash, String, Symbol] :with Attributes (usually hidden) to serialize additionally
510
- # @option opts [Boolean] :validate Validates provided modifiers (Default is true)
511
- #
512
- def initialize(opts = nil)
513
- @opts =
514
- if opts.nil? || opts.empty?
515
- FROZEN_EMPTY_HASH
516
- else
517
- opts.transform_keys!(&:to_sym)
518
- parse_modifiers(opts)
519
- end
520
-
521
- self.class::CheckInitiateParams.new(@opts).validate if opts&.fetch(:check_initiate_params) { config.check_initiate_params }
522
-
523
- @plan = self.class::SeregaPlan.call(@opts)
666
+ # Prepares a serializer with a field selection. The options are the field
667
+ # options of Serega::ClassMethods#to_h.
668
+ #
669
+ # ```ruby
670
+ # serializer = UserSerializer.new(only: [:first_name])
671
+ # serializer.to_h(user) # => {first_name: "Bruce"}
672
+ # serializer.to_h(users) # => [{first_name: "Bruce"}, {first_name: "Alfred"}]
673
+ # ```
674
+ #
675
+ def initialize(only: nil, with: nil, except: nil, preset: nil, check_selection: nil)
676
+ @plan = self.class.plan_cache.fetch(only, with, except, preset, check_selection: check_selection)
677
+ @direct_hash_builder = @plan.direct_hash_builder
524
678
  end
525
679
 
526
- #
527
680
  # Plan for serialization.
528
681
  # This plan can be traversed to find serialized attributes and nested attributes.
529
- #
530
- # @return [Serega::SeregaPlan] Serialization plan
531
- # @private
532
- attr_reader :plan
682
+ attr_reader :plan # :nodoc:
683
+
684
+ # Patched in:
685
+ # - plugin :root (takes the options of plugins)
533
686
 
534
687
  #
535
- # Serializes provided object to Hash
536
- #
537
- # @param object [Object] Serialized object
538
- # @param opts [Hash, nil] Serializing options
539
- # @option opts [Hash] :context Serialization context
540
- # @option opts [Boolean] :many Set true if provided multiple objects (Default `object.is_a?(Enumerable) && !object.is_a?(Hash) && !object.is_a?(Struct)`)
688
+ # Serializes an object or a list to a Hash or an Array of Hashes, with the
689
+ # serialization options of Serega::ClassMethods#to_h
541
690
  #
542
- # @return [Hash] Serialization result
691
+ # ```ruby
692
+ # UserSerializer.new.to_h(user, context: {admin: true})
693
+ # ```
543
694
  #
544
- def call(object, opts = nil)
545
- opts = normalize_serialization_opts(opts)
546
- object = prepare_objects(object, opts[:context])
547
- opts = prepare_initial_serialization_opts(object, opts)
548
- serialize(object, opts)
549
- end
695
+ def call(object, context: nil, many: nil)
696
+ # One Hash source of a flat plan skips #serialize_to and the run: 73 ns
697
+ # and 1 object instead of 136 ns and 3 objects (Ruby 4.0, YJIT).
698
+ builder = @direct_hash_builder
699
+ if builder && object && !many && (context.nil? || context.is_a?(Hash))
700
+ many = object.instance_of?(Array) || SeregaUtils::CollectionDetector.call(object, @plan.collection_classes) if many.nil?
701
+ return builder.call_one(object, context.nil? ? FROZEN_EMPTY_HASH : context) unless many
702
+ end
550
703
 
551
- # @see #call
552
- def to_h(object, opts = nil)
553
- call(object, opts)
704
+ serialize_to(:hash, object, context, many, FROZEN_EMPTY_HASH)
554
705
  end
555
706
 
556
- #
557
- # Serializes provided object to Data objects
707
+ alias_method :to_h, :call
708
+
558
709
  # Patched in:
559
- # - plugin :root (adds a data-object for a root level keys)
560
- #
561
- # @param object [Object] Serialized object
562
- # @param opts [Hash, nil] Serializing options
563
- # @option opts [Hash] :context Serialization context
564
- # @option opts [Boolean] :many Set true if provided multiple objects (Default `object.is_a?(Enumerable) && !object.is_a?(Hash) && !object.is_a?(Struct)`)
710
+ # - plugin :root (takes the options of plugins)
711
+
565
712
  #
566
- # @return [Data] Serialization result
713
+ # Serializes like #to_h, to `Data` objects
567
714
  #
568
- def to_data(object, opts = nil)
569
- opts = normalize_serialization_opts(opts)
570
- object = prepare_objects(object, opts[:context])
571
- opts = prepare_initial_serialization_opts(object, opts)
572
- serialized_data = serialize(object, opts)
573
- self.class::SeregaDataBuilder.call(self, serialized_data)
574
- end
575
-
576
- private
577
-
578
- attr_reader :opts
579
-
580
- def config
581
- self.class.config
715
+ def to_data(object, context: nil, many: nil)
716
+ serialize_to(:data, object, context, many, FROZEN_EMPTY_HASH)
582
717
  end
583
718
 
584
- def parse_modifiers(opts)
585
- result = {}
586
-
587
- opts.each do |key, value|
588
- value = parse_modifier(value) if (key == :only) || (key == :except) || (key == :with)
589
- result[key] = value
590
- end
719
+ # Patched in:
720
+ # - plugin :root (takes the options of plugins)
591
721
 
592
- result
722
+ #
723
+ # Serializes like #to_h, to `Struct` objects
724
+ #
725
+ def to_struct(object, context: nil, many: nil)
726
+ serialize_to(:struct, object, context, many, FROZEN_EMPTY_HASH)
593
727
  end
594
728
 
595
729
  # Patched in:
596
- # - plugin :string_modifiers (parses string modifiers differently)
597
- def parse_modifier(value)
598
- SeregaUtils::ToHash.call(value)
730
+ # - plugin :root (takes the options of plugins)
731
+
732
+ #
733
+ # Serializes like #to_h, to a JSON String: `JSON.generate` of the #to_h
734
+ # result
735
+ #
736
+ def to_json(object, context: nil, many: nil)
737
+ JSON.generate(call(object, context: context, many: many))
599
738
  end
600
739
 
601
- def normalize_serialization_opts(opts)
602
- opts = opts ? opts.transform_keys(&:to_sym) : {}
603
- self.class::CheckSerializeParams.new(opts).validate unless opts.empty?
740
+ private
604
741
 
605
- opts[:context] ||= {}
606
- opts
742
+ # Serializes the object with the serialization options. `opts` holds the
743
+ # options other than :context and :many.
744
+ def serialize_to(mode, object, context, many, opts)
745
+ SeregaValidations::CheckSerializeKeywords.call(context, many)
746
+ context ||= FROZEN_EMPTY_HASH
747
+ object = prepare_objects(object, context) if self.class.prepare_initial_objects_signature
748
+ many = object.instance_of?(Array) || SeregaUtils::CollectionDetector.call(object, @plan.collection_classes) if many.nil?
749
+ serialize(object, opts, context, many, mode)
607
750
  end
608
751
 
609
752
  def prepare_objects(objects, context)
610
753
  handler = self.class.prepare_initial_objects
611
- return objects unless handler
612
754
 
613
755
  case self.class.prepare_initial_objects_signature
614
756
  when "1" then handler.call(objects)
@@ -617,24 +759,17 @@ class Serega
617
759
  end
618
760
  end
619
761
 
620
- def prepare_initial_serialization_opts(object, opts)
621
- opts[:level_queue] = SeregaEngine::LevelQueue.new
622
- opts[:many] = SeregaUtils::CollectionDetector.call(object) unless opts.key?(:many)
623
- opts[:plan] = plan
624
- opts
625
- end
626
-
627
762
  # Patched in:
628
763
  # - plugin :root (wraps result `{ root => result }`)
629
764
  # - plugin :context_metadata (adds context metadata to final result)
630
765
  # - plugin :metadata (adds metadata to final result)
631
- def serialize(object, opts)
632
- result = self.class::SeregaObjectSerializer.new(**opts).serialize(object)
633
- opts[:level_queue].run
634
- result
766
+ def serialize(object, _opts, context, many, mode)
767
+ SeregaEngine::Run.call(@plan, object, many, mode, context)
635
768
  end
636
769
  end
637
770
 
638
771
  extend ClassMethods
639
772
  include InstanceMethods
773
+
774
+ initialize_definition(SeregaConfig.new, {})
640
775
  end