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/config.rb CHANGED
@@ -1,139 +1,95 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  class Serega
4
+ # Config of a serializer, `config` in a serializer class. Subclasses copy
5
+ # the config of their parent and can change it.
4
6
  #
5
- # Stores serialization config
7
+ # ```ruby
8
+ # class AppSerializer < Serega
9
+ # config.auto_preload = true
10
+ # config.hide_by_default = :auto
11
+ # end
12
+ # ```
6
13
  #
14
+ # See [Configuration](https://github.com/andreyruby/serega/blob/master/docs/configuration.md).
7
15
  class SeregaConfig
8
16
  # :nocov: We can't use both :oj and :json adapters together
9
17
 
10
18
  #
11
19
  # Default config options
12
20
  #
13
- DEFAULTS = {
21
+ DEFAULTS = { # :nodoc:
14
22
  plugins: [],
15
- initiate_keys: %i[only with except check_initiate_params].freeze,
16
- attribute_keys: %i[
17
- method
18
- value
19
- serializer
20
- many
21
- hide
22
- const
23
- delegate
24
- default
25
- preload
26
- batch
27
- base_serializer
28
- hash_access
29
- ].freeze,
30
23
  serialize_keys: %i[context many].freeze,
31
24
  check_attribute_name: true,
32
- check_initiate_params: true,
25
+ require_many: false,
26
+ check_selection: true,
33
27
  delegate_default_allow_nil: false,
34
- max_cached_plans_per_serializer_count: 0,
28
+ max_cached_plans_per_serializer_count: 20,
29
+ depth_limit: nil,
35
30
  auto_preload: {has_delegate_option: false, has_serializer_option: false},
36
31
  auto_preload_excluded_methods: %i[itself __getobj__].freeze,
37
32
  hide_by_default: false,
33
+ compact: false,
34
+ key_transform: nil,
38
35
  batch_id_option: :id,
39
36
  base_serializer: nil,
40
37
  hash_access: {default_mode: :symbol, default_allow_missing_key: false}
41
38
  }.freeze
42
39
  # :nocov:
43
40
 
44
- # SeregaConfig Instance methods
41
+ # Config options
45
42
  module SeregaConfigInstanceMethods
46
- #
47
43
  # Shows current config as Hash
48
- #
49
- # @return [Hash] config options
50
- #
51
- attr_reader :opts
44
+ attr_reader :opts # :nodoc:
52
45
 
53
- #
54
46
  # Initializes new config instance.
55
- #
56
- # @param opts [Hash] Initial config options
57
- #
58
- def initialize(opts = nil)
47
+ def initialize(opts = nil) # :nodoc:
59
48
  opts ||= DEFAULTS
60
49
  @opts = SeregaUtils::EnumDeepDup.call(opts)
50
+ @hash_access = nil
51
+ @plugin_configs = {}
61
52
  end
62
53
 
63
- #
64
54
  # Shows used plugins
65
- #
66
- # @return [Array] Used plugins
67
- #
68
- def plugins
55
+ def plugins # :nodoc:
69
56
  opts.fetch(:plugins)
70
57
  end
71
58
 
72
- # Returns options names allowed in `Serega#new` method
73
- # @return [Array<Symbol>] allowed options keys
74
- def initiate_keys
75
- opts.fetch(:initiate_keys)
76
- end
77
-
78
- # Returns options names allowed in `Serega.attribute` method
79
- # @return [Array<Symbol>] Allowed options keys for attribute initialization
80
- def attribute_keys
81
- opts.fetch(:attribute_keys)
82
- end
83
-
84
59
  # Returns options names allowed in `call, to_h` methods
85
- # @return [Array<Symbol>] Allowed options keys for serialization
86
- def serialize_keys
60
+ def serialize_keys # :nodoc:
87
61
  opts.fetch(:serialize_keys)
88
62
  end
89
63
 
90
- # Returns :check_initiate_params config option
91
- # @return [Boolean] Current :check_initiate_params config option
92
- def check_initiate_params
93
- opts.fetch(:check_initiate_params)
64
+ # Whether unknown fields of `only:`, `except:` and `with:` raise
65
+ # `Serega::AttributeNotExist`. `true` by default.
66
+ def check_selection
67
+ opts.fetch(:check_selection)
94
68
  end
95
69
 
96
- # Sets :check_initiate_params config option
97
- #
98
- # @param value [Boolean] Set :check_initiate_params config option
99
- #
100
- # @return [Boolean] :check_initiate_params config option
101
- def check_initiate_params=(value)
102
- raise SeregaError, "Must have boolean value, #{value.inspect} provided" if (value != true) && (value != false)
103
- opts[:check_initiate_params] = value
70
+ # Sets #check_selection
71
+ def check_selection=(value)
72
+ opts[:check_selection] = checked_boolean(value)
104
73
  end
105
74
 
106
- # Returns :delegate_default_allow_nil config option
107
- # @return [Boolean] Current :delegate_default_allow_nil config option
75
+ # Default `allow_nil:` of the `:delegate` attribute option. `false` by
76
+ # default.
108
77
  def delegate_default_allow_nil
109
78
  opts.fetch(:delegate_default_allow_nil)
110
79
  end
111
80
 
112
- # Sets :delegate_default_allow_nil config option
113
- #
114
- # @param value [Boolean] Set :delegate_default_allow_nil config option
115
- #
116
- # @return [Boolean] :delegate_default_allow_nil config option
81
+ # Sets #delegate_default_allow_nil
117
82
  def delegate_default_allow_nil=(value)
118
- raise SeregaError, "Must have boolean value, #{value.inspect} provided" if (value != true) && (value != false)
119
- opts[:delegate_default_allow_nil] = value
83
+ opts[:delegate_default_allow_nil] = checked_boolean(value)
120
84
  end
121
85
 
122
- # Returns :auto_preload_excluded_methods config option — methods that are
123
- # never auto-preloaded, as they return the serialized object itself and
124
- # not an association
125
- # @return [Array<Symbol>] Current :auto_preload_excluded_methods config option
86
+ # Methods that #auto_preload never preloads, as they return the object
87
+ # itself. `[:itself, :__getobj__]` by default.
126
88
  def auto_preload_excluded_methods
127
89
  opts.fetch(:auto_preload_excluded_methods)
128
90
  end
129
91
 
130
- # Sets :auto_preload_excluded_methods config option — methods that are
131
- # never auto-preloaded. Applies to the `:method` option of attributes
132
- # with a serializer and to the `delegate: {to: ...}` option.
133
- #
134
- # @param value [Array<Symbol>] Method names to skip in auto-preload
135
- #
136
- # @return [Array<Symbol>] New :auto_preload_excluded_methods config option
92
+ # Sets #auto_preload_excluded_methods
137
93
  def auto_preload_excluded_methods=(value)
138
94
  unless value.is_a?(Array) && value.all?(Symbol)
139
95
  raise SeregaError, "Must be an Array of Symbols, #{value.inspect} provided"
@@ -142,41 +98,31 @@ class Serega
142
98
  opts[:auto_preload_excluded_methods] = value
143
99
  end
144
100
 
145
- # Returns :base_serializer config option — the parent class for nested
146
- # serializers defined with attribute blocks
147
- # @return [Class, nil] Current :base_serializer config option
101
+ # Parent class of nested serializers defined with an attribute block.
102
+ # `nil` by default.
148
103
  def base_serializer
149
104
  opts.fetch(:base_serializer)
150
105
  end
151
106
 
152
- # Sets :base_serializer config option — the parent class for nested
153
- # serializers defined with attribute blocks. Usually a settings-only
154
- # serializer, e.g. `config.base_serializer = self` in an application
155
- # base serializer class.
107
+ # Sets #base_serializer, a Serega subclass
156
108
  #
157
- # @param value [Class] Serega or its subclass
158
- #
159
- # @return [Class] New :base_serializer config option
109
+ # ```ruby
110
+ # config.base_serializer = self
111
+ # ```
160
112
  def base_serializer=(value)
161
113
  raise SeregaError, "Must be a Serega subclass, #{value.inspect} provided" if !value.is_a?(Class) || !(value <= Serega)
162
114
 
163
115
  opts[:base_serializer] = value
164
116
  end
165
117
 
166
- # Returns :hide_by_default config option
167
- # @return [Boolean, Symbol] Current :hide_by_default config option
118
+ # Which attributes are hidden without the `:hide` option: `false` for none
119
+ # (the default), `true` for all, `:auto` for attributes with preloads or
120
+ # batch loaders.
168
121
  def hide_by_default
169
122
  opts.fetch(:hide_by_default)
170
123
  end
171
124
 
172
- # Sets :hide_by_default config option
173
- #
174
- # @param value [Boolean, Symbol] Accepted values:
175
- # - false (default) — nothing is hidden by default
176
- # - true — all attributes are hidden by default
177
- # - :auto — hides attributes that declare :preload or :batch
178
- #
179
- # @return [Boolean, Symbol] New :hide_by_default config option
125
+ # Sets #hide_by_default
180
126
  def hide_by_default=(value)
181
127
  opts[:hide_by_default] =
182
128
  case value
@@ -187,13 +133,40 @@ class Serega
187
133
  end
188
134
  end
189
135
 
190
- # @return [Hash] auto_preload option
136
+ # Whether serialized Hashes leave out keys with `nil` values, as
137
+ # `Hash#compact` does. `false` by default.
138
+ def compact
139
+ opts.fetch(:compact)
140
+ end
141
+
142
+ # Sets #compact
143
+ def compact=(value)
144
+ opts[:compact] = checked_boolean(value)
145
+ end
146
+
147
+ # How attribute names become serialized keys: `nil` (names as they are,
148
+ # the default), `:camel_case` (`first_name` gives `firstName`), or a
149
+ # callable that receives the name Symbol and returns the key. A String
150
+ # key stays a String in the serialized Hash. The attribute name is the
151
+ # key as a Symbol, thus `only:`, `except:` and `with:` take it.
152
+ def key_transform
153
+ opts.fetch(:key_transform)
154
+ end
155
+
156
+ # Sets #key_transform
157
+ def key_transform=(value)
158
+ opts[:key_transform] = checked_key_transform(value)
159
+ end
160
+
161
+ # Attributes that get preloads automatically: `:delegate` attributes with
162
+ # `has_delegate_option` and `:serializer` attributes with
163
+ # `has_serializer_option`. Both are `false` by default.
191
164
  def auto_preload
192
165
  opts.fetch(:auto_preload)
193
166
  end
194
167
 
195
- # Validates and sets auto_preload option
196
- # @return [Hash] New auto_preload option with attributes that trigger auto preload
168
+ # Sets #auto_preload: `true` or `false` for both kinds of attributes, or a
169
+ # Hash with `has_delegate_option` and `has_serializer_option`
197
170
  def auto_preload=(value)
198
171
  opts[:auto_preload] =
199
172
  case value
@@ -207,85 +180,114 @@ class Serega
207
180
  end
208
181
  end
209
182
 
210
- # Returns the hash_access config object
211
- # @return [Serega::SeregaConfig::HashAccessConfig] hash_access config object
183
+ # Builds lazy config objects before freezing, thus a frozen config
184
+ # returns them
185
+ def freeze # :nodoc:
186
+ hash_access
187
+ super
188
+ end
189
+
190
+ # Defaults of the `hash_access:` attribute option
212
191
  def hash_access
213
192
  @hash_access ||= HashAccessConfig.new(opts.fetch(:hash_access))
214
193
  end
215
194
 
216
- # Returns :max_cached_plans_per_serializer_count config option
217
- # @return [Boolean] Current :max_cached_plans_per_serializer_count config option
195
+ # How many serialization plans with field selection the serializer
196
+ # caches, `20` by default. `0` disables the cache.
218
197
  def max_cached_plans_per_serializer_count
219
198
  opts.fetch(:max_cached_plans_per_serializer_count)
220
199
  end
221
200
 
222
- # Sets :max_cached_plans_per_serializer_count config option
223
- #
224
- # @param value [Boolean] Set :check_initiate_params config option
225
- #
226
- # @return [Boolean] New :max_cached_plans_per_serializer_count config option
201
+ # Sets #max_cached_plans_per_serializer_count
227
202
  def max_cached_plans_per_serializer_count=(value)
228
203
  raise SeregaError, "Must have Integer value, #{value.inspect} provided" unless value.is_a?(Integer)
229
204
  opts[:max_cached_plans_per_serializer_count] = value
230
205
  end
231
206
 
232
- # Returns whether attributes names check is disabled
207
+ # Deepest nesting of serialized fields, `nil` for no limit (the default).
208
+ # The limit of the serializer that starts the serialization applies.
209
+ def depth_limit
210
+ opts.fetch(:depth_limit)
211
+ end
212
+
213
+ # Sets #depth_limit: a positive Integer or `nil`
214
+ def depth_limit=(value)
215
+ valid = value.nil? || (value.is_a?(Integer) && value.positive?)
216
+ raise SeregaError, "Must have positive Integer or nil value, #{value.inspect} provided" unless valid
217
+ opts[:depth_limit] = value
218
+ end
219
+
220
+ # Whether attribute names may contain only `a-z`, `A-Z`, `0-9`, `_`, `-`
221
+ # and `~`. `true` by default.
233
222
  def check_attribute_name
234
223
  opts.fetch(:check_attribute_name)
235
224
  end
236
225
 
237
- # Sets :check_attribute_name config option
238
- #
239
- # @param value [Boolean] Set :check_attribute_name config option
240
- #
241
- # @return [Boolean] New :check_attribute_name config option
226
+ # Sets #check_attribute_name
242
227
  def check_attribute_name=(value)
243
- raise SeregaError, "Must have boolean value, #{value.inspect} provided" if (value != true) && (value != false)
244
- opts[:check_attribute_name] = value
228
+ opts[:check_attribute_name] = checked_boolean(value)
229
+ end
230
+
231
+ # Whether every relation, an attribute with `:serializer` or a block,
232
+ # must have the `:many` option. `false` by default.
233
+ def require_many
234
+ opts.fetch(:require_many)
245
235
  end
246
236
 
247
- # Returns current batch_id_option
237
+ # Sets #require_many
238
+ def require_many=(value)
239
+ opts[:require_many] = checked_boolean(value)
240
+ end
241
+
242
+ # Method that returns the id of an object for batch loaders, `:id` by
243
+ # default
248
244
  def batch_id_option
249
245
  opts.fetch(:batch_id_option)
250
246
  end
251
247
 
252
- # Sets :batch_id_option config option
253
- #
254
- # @param value [Symbol] Set :batch_id_option config option
255
- #
256
- # @return [Symbol] New :check_attribute_name config option
248
+ # Sets #batch_id_option
257
249
  def batch_id_option=(value)
258
250
  raise SeregaError, "Must have Symbol value, #{value.inspect} provided" unless value.is_a?(Symbol)
259
251
  opts[:batch_id_option] = value
260
252
  end
253
+
254
+ private
255
+
256
+ def checked_key_transform(value)
257
+ return value if value.nil? || value == :camel_case
258
+
259
+ params =
260
+ if value.respond_to?(:parameters) then value.parameters
261
+ elsif value.respond_to?(:call) then value.method(:call).parameters
262
+ end
263
+ return value if params&.size == 1 && %i[req opt].include?(params[0][0])
264
+
265
+ raise SeregaError, "Must be nil, :camel_case, or a callable with one parameter, #{value.inspect} provided"
266
+ end
267
+
268
+ def checked_boolean(value)
269
+ raise SeregaError, "Must have boolean value, #{value.inspect} provided" unless value == true || value == false
270
+
271
+ value
272
+ end
261
273
  end
262
274
 
263
- #
264
- # Config for the `hash_access:` attribute option
265
- #
275
+ # Defaults of the `hash_access:` attribute option, `config.hash_access`
266
276
  class HashAccessConfig
267
- # @return [Hash] hash_access config options
268
- attr_reader :opts
277
+ # hash_access config options
278
+ attr_reader :opts # :nodoc:
269
279
 
270
- #
271
280
  # Initializes HashAccessConfig object
272
- #
273
- # @param opts [Hash] hash_access config options
274
- #
275
- # @return [Serega::SeregaConfig::HashAccessConfig]
276
- #
277
- def initialize(opts)
281
+ def initialize(opts) # :nodoc:
278
282
  @opts = opts
279
283
  end
280
284
 
281
- # @return [Symbol] mode used by `hash_access: true` (default :symbol)
285
+ # Mode of `hash_access: true`: `:symbol` (the default) or `:string` keys
282
286
  def default_mode
283
287
  opts.fetch(:default_mode)
284
288
  end
285
289
 
286
- # Sets the mode used by `hash_access: true`
287
- # @param value [Symbol] one of :symbol, :string
288
- # @return [Symbol] new default mode
290
+ # Sets #default_mode
289
291
  def default_mode=(value)
290
292
  unless AttributeValueResolvers::HashAccessResolver::MODES.include?(value)
291
293
  raise SeregaError, "Invalid hash_access default_mode #{value.inspect}. Allowed modes: :symbol, :string"
@@ -294,14 +296,13 @@ class Serega
294
296
  opts[:default_mode] = value
295
297
  end
296
298
 
297
- # @return [Boolean] allow_missing_key used when an attribute omits it
299
+ # Whether a missing Hash key gives `nil` instead of raising `KeyError`.
300
+ # `false` by default.
298
301
  def default_allow_missing_key
299
302
  opts.fetch(:default_allow_missing_key)
300
303
  end
301
304
 
302
- # Sets the allow_missing_key used when an attribute omits it
303
- # @param value [Boolean]
304
- # @return [Boolean] new default allow_missing_key
305
+ # Sets #default_allow_missing_key
305
306
  def default_allow_missing_key=(value)
306
307
  unless value == true || value == false
307
308
  raise SeregaError, "Invalid hash_access default_allow_missing_key #{value.inspect}. Must be a Boolean"
@@ -312,6 +313,5 @@ class Serega
312
313
  end
313
314
 
314
315
  include SeregaConfigInstanceMethods
315
- extend Serega::SeregaHelpers::SerializerClassHelper
316
316
  end
317
317
  end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Serega
4
+ module SeregaEngine # :nodoc:
5
+ #
6
+ # Pulls of relation sources. A pull says what to take for one relation
7
+ # source from the serialized objects of its child group:
8
+ # - the count of a collection: an Array of this count of serialized objects
9
+ # - SINGLE_SOURCE for one source: one serialized object
10
+ # - nil for nil: nothing, the relation value is nil
11
+ # - SKIP for a relation skipped by its condition: nothing, the relation
12
+ # value is SKIP
13
+ #
14
+ module Pulls # :nodoc:
15
+ # Pull of one source that is not in a collection. Its relation value is
16
+ # one serialized object, and not an Array.
17
+ SINGLE_SOURCE = Object.new.freeze
18
+
19
+ module_function
20
+
21
+ # Appends the source(s) of one relation source to sources, and returns
22
+ # its pull. The generated `#collect` of a result builder writes the
23
+ # same steps inline.
24
+ def append(sources, relation_source, many, known_classes)
25
+ return if relation_source.nil?
26
+
27
+ if many != false && (relation_source.instance_of?(Array) || SeregaUtils::CollectionDetector.call(relation_source, known_classes))
28
+ collection = relation_source.to_a
29
+ sources.concat(collection)
30
+ collection.size
31
+ else
32
+ sources << relation_source
33
+ many ? 1 : SINGLE_SOURCE # `many` on, but a sole source was given — wrap it, don't raise
34
+ end
35
+ end
36
+
37
+ # Takes the relation value of each pull from the front of the
38
+ # serialized objects. The serialized objects follow the order of the
39
+ # pulls. Empties the serialized objects.
40
+ def take!(serialized, pulls)
41
+ pulls.map do |pull|
42
+ case pull
43
+ when Integer then serialized.shift(pull)
44
+ when SINGLE_SOURCE then serialized.shift
45
+ else pull # nil or SKIP
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Serega
4
+ #
5
+ # Serialization engine
6
+ #
7
+ module SeregaEngine # :nodoc:
8
+ # Value of an attribute skipped by its conditions. It is also the pull of
9
+ # a skipped relation.
10
+ SKIP = Object.new.freeze
11
+
12
+ #
13
+ # One serialization run. Serializes the source(s) with a plan, and all
14
+ # their relation sources. A source is an object to serialize.
15
+ #
16
+ # The run makes source groups. A group holds all sources of one plan, for
17
+ # example the posts of all users, thus batch loaders and preloads run once
18
+ # per group. The run serializes the groups in two passes:
19
+ # - Discover pass, from the root group down. Each group runs its preloads
20
+ # and makes one child group per relation.
21
+ # - Build pass, from the last group up. Each group builds its serialized
22
+ # objects. The serialized related objects are ready at this time.
23
+ #
24
+ class Run # :nodoc:
25
+ class << self
26
+ # Serializes the object(s) with the plan in a new run. A flat plan
27
+ # builds its serialized object(s) with its result builder, without a
28
+ # run, and one source without the sources Array. Skipping the run and
29
+ # its source group takes 136 ns and 3 objects instead of 343 ns and 8
30
+ # objects for one Hash source (Ruby 4.0, YJIT).
31
+ def call(plan, object, many, mode, context)
32
+ return new(mode, context).call(plan, object, many: many) unless plan.flat?
33
+ return if object.nil?
34
+
35
+ builder = plan.result_builder(mode)
36
+ return builder.call_one(object, context) if many == false
37
+
38
+ sources = []
39
+ pull = Pulls.append(sources, object, many, plan.collection_classes)
40
+ Pulls::SINGLE_SOURCE.equal?(pull) ? builder.call_one(object, context) : builder.call(sources, context, nil, nil)
41
+ end
42
+ end
43
+
44
+ # Serialization mode
45
+ attr_reader :mode
46
+
47
+ # Serialization context
48
+ attr_reader :context
49
+
50
+ def initialize(mode, context)
51
+ @mode = mode
52
+ @context = context
53
+ end
54
+
55
+ # Serializes the object(s) with the plan.
56
+ def call(plan, object, many:)
57
+ return if object.nil?
58
+
59
+ root_group = root_source_group(plan, object, many)
60
+ source_groups = discover(root_group)
61
+ build(source_groups)
62
+ root_group.root_value
63
+ end
64
+
65
+ # Makes a source group of the plan.
66
+ def new_source_group(plan, sources, pulls)
67
+ SeregaSourceGroup.new(self, plan, sources, pulls)
68
+ end
69
+
70
+ private
71
+
72
+ # Makes the root group: the root source(s) with one pull
73
+ def root_source_group(plan, object, many)
74
+ sources = []
75
+ pull = Pulls.append(sources, object, many, plan.collection_classes)
76
+ new_source_group(plan, sources, [pull])
77
+ end
78
+
79
+ # Discovers the root group and its child groups, from the root down.
80
+ # Returns all groups in discover order: a child group comes after its
81
+ # parent group.
82
+ def discover(root_group)
83
+ source_groups = [root_group]
84
+ index = 0
85
+
86
+ while index < source_groups.size
87
+ source_groups.concat(source_groups[index].discover)
88
+ index += 1
89
+ end
90
+
91
+ source_groups
92
+ end
93
+
94
+ # Builds the groups from the last one up, thus a child group is built
95
+ # before its parent group
96
+ def build(source_groups)
97
+ source_groups.reverse_each(&:build)
98
+ end
99
+ end
100
+ end
101
+ end
data/lib/serega/errors.rb CHANGED
@@ -1,23 +1,75 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  class Serega
4
+ # Raised on invalid definitions and options, and on changes of a locked
5
+ # serializer. Parent class of the other Serega errors.
4
6
  #
5
- # Base exception class
6
- #
7
+ # See [Errors](https://github.com/andreyruby/serega/blob/master/docs/errors.md).
7
8
  class SeregaError < StandardError; end
8
9
 
9
- # Raised when serializer is initiated using not existing attribute
10
+ # Raised when `only:`, `except:` or `with:` names an unknown field
11
+ #
12
+ # ```ruby
13
+ # UserSerializer.to_h(user, only: [:nickname, {friends: :age}])
14
+ # # => Serega::AttributeNotExist: Not existing attributes: nickname, friends(age)
15
+ # ```
10
16
  #
11
- # @example
12
- # Serega.new(only: 'FOO')
13
- # # => Attribute 'FOO' not exists (Serega::AttributeNotExist)
17
+ # See [Unknown fields](https://github.com/andreyruby/serega/blob/master/docs/selecting-fields.md#unknown-fields).
14
18
  class AttributeNotExist < SeregaError
15
- attr_reader :serializer, :attributes
19
+ # Serializer that has no such fields
20
+ attr_reader :serializer
21
+
22
+ # Unknown fields, for example `["nickname", "friends(age)"]`
23
+ attr_reader :attributes
16
24
 
17
- def initialize(message = nil, serializer = nil, attributes = nil)
25
+ def initialize(message = nil, serializer = nil, attributes = nil) # :nodoc:
18
26
  super(message)
19
27
  @serializer = serializer
20
28
  @attributes = attributes
21
29
  end
22
30
  end
31
+
32
+ # Raised when `preset:` names an undefined preset
33
+ #
34
+ # ```ruby
35
+ # UserSerializer.to_h(user, preset: :admin)
36
+ # # => Serega::PresetNotExist: Preset :admin is not defined in UserSerializer
37
+ # ```
38
+ #
39
+ # See [Presets](https://github.com/andreyruby/serega/blob/master/docs/selecting-fields.md#presets).
40
+ class PresetNotExist < SeregaError
41
+ # Serializer that has no such preset
42
+ attr_reader :serializer
43
+
44
+ # Name of the undefined preset, for example `:admin`
45
+ attr_reader :preset
46
+
47
+ def initialize(message = nil, serializer = nil, preset = nil) # :nodoc:
48
+ super(message)
49
+ @serializer = serializer
50
+ @preset = preset
51
+ end
52
+ end
53
+
54
+ # Raised when fields nest deeper than `config.depth_limit` of the
55
+ # serializer that starts the serialization
56
+ #
57
+ # ```ruby
58
+ # UserSerializer.to_h(user, with: {friends: :friends})
59
+ # # => Serega::DepthLimitError: Depth limit was exceeded
60
+ # ```
61
+ #
62
+ # See [Depth limit](https://github.com/andreyruby/serega/blob/master/docs/configuration.md#depth-limit).
63
+ class DepthLimitError < SeregaError
64
+ # Path that exceeds the limit, and on the next line a hint to increase the limit:
65
+ #
66
+ # UserSerializer (depth limit: 2) -> friends -> friends
67
+ # (hint: if the nesting is not a cycle, increase config.depth_limit of UserSerializer)
68
+ attr_reader :details
69
+
70
+ def initialize(message = nil, details = nil) # :nodoc:
71
+ super(message)
72
+ @details = details
73
+ end
74
+ end
23
75
  end