serega 0.50.0 → 0.51.1

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 (58) hide show
  1. checksums.yaml +4 -4
  2. data/VERSION +1 -1
  3. data/lib/serega/attribute/serializer_reference.rb +27 -0
  4. data/lib/serega/attribute/value_code.rb +63 -0
  5. data/lib/serega/attribute.rb +80 -102
  6. data/lib/serega/attribute_normalizer.rb +43 -17
  7. data/lib/serega/attribute_normalizers/preloads.rb +5 -4
  8. data/lib/serega/attribute_value_resolvers/base.rb +35 -0
  9. data/lib/serega/attribute_value_resolvers/batch.rb +14 -1
  10. data/lib/serega/attribute_value_resolvers/callable.rb +52 -0
  11. data/lib/serega/attribute_value_resolvers/const.rb +11 -1
  12. data/lib/serega/attribute_value_resolvers/delegate.rb +12 -2
  13. data/lib/serega/attribute_value_resolvers/hash_access.rb +19 -4
  14. data/lib/serega/attribute_value_resolvers/keyword.rb +10 -3
  15. data/lib/serega/attribute_values.rb +4 -18
  16. data/lib/serega/conditions.rb +26 -1
  17. data/lib/serega/config.rb +45 -6
  18. data/lib/serega/engine/pulls.rb +3 -16
  19. data/lib/serega/engine/run.rb +4 -9
  20. data/lib/serega/errors.rb +28 -3
  21. data/lib/serega/formatters/callable.rb +44 -0
  22. data/lib/serega/formatters/method.rb +55 -0
  23. data/lib/serega/formatters.rb +27 -0
  24. data/lib/serega/plan/cache.rb +83 -60
  25. data/lib/serega/plan/depth_limit.rb +55 -0
  26. data/lib/serega/plan/per_ractor_cache.rb +11 -6
  27. data/lib/serega/plan/point.rb +67 -0
  28. data/lib/serega/plan/presets.rb +116 -0
  29. data/lib/serega/plan/selection.rb +104 -0
  30. data/lib/serega/plan/selection_planner.rb +50 -0
  31. data/lib/serega/plan.rb +45 -55
  32. data/lib/serega/plugins/metadata/meta_attribute.rb +17 -1
  33. data/lib/serega/plugins/metadata/metadata.rb +1 -10
  34. data/lib/serega/plugins/root/root.rb +11 -8
  35. data/lib/serega/presenter.rb +20 -0
  36. data/lib/serega/result_builder.rb +1 -1
  37. data/lib/serega/result_code/attribute_point_code.rb +117 -0
  38. data/lib/serega/result_code/point_code.rb +54 -0
  39. data/lib/serega/result_code/relation_point_code.rb +112 -0
  40. data/lib/serega/result_code.rb +41 -85
  41. data/lib/serega/source_group.rb +37 -68
  42. data/lib/serega/utils/camel_case.rb +22 -0
  43. data/lib/serega/utils/collection_detector.rb +3 -2
  44. data/lib/serega/utils/{parse_string_modifiers.rb → parse_string_selection.rb} +2 -2
  45. data/lib/serega/utils/ruby_literal.rb +28 -0
  46. data/lib/serega/validations/attribute/check_opt_preset.rb +34 -0
  47. data/lib/serega/validations/attribute/check_opt_selection.rb +41 -0
  48. data/lib/serega/validations/check_attribute_params.rb +4 -4
  49. data/lib/serega/validations/check_definition_selection.rb +21 -0
  50. data/lib/serega/validations/check_preset_params.rb +103 -0
  51. data/lib/serega/validations/check_relation_selection.rb +31 -0
  52. data/lib/serega/validations/check_selection.rb +89 -0
  53. data/lib/serega.rb +118 -50
  54. data/sig/serega.rbs +23 -7
  55. metadata +32 -10
  56. data/lib/serega/formatter.rb +0 -98
  57. data/lib/serega/plan_point.rb +0 -58
  58. data/lib/serega/validations/initiate/check_modifiers.rb +0 -87
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Serega
4
+ module SeregaValidations # :nodoc:
5
+ #
6
+ # Checks the attributes that the `only`, `with` and `except` options of
7
+ # a relation name
8
+ #
9
+ class CheckRelationSelection # :nodoc:
10
+ class << self
11
+ # Checks the options of a relation when its plan is built, for a
12
+ # serializer given as a String or a Proc, or defined with a block. A
13
+ # serializer class is checked when the attribute is defined.
14
+ def call(attribute, serializer)
15
+ return if attribute.initials[:opts][:serializer].is_a?(Class)
16
+
17
+ check(attribute.name, serializer, attribute.selection, CheckSelection)
18
+ end
19
+
20
+ # Raises AttributeNotExist that names the relation for attributes
21
+ # the selection names and the serializer does not have
22
+ def check(name, serializer, selection, validator)
23
+ validator.new.call(serializer, selection[:only], selection[:with], selection[:except])
24
+ rescue AttributeNotExist => error
25
+ attributes = error.attributes
26
+ raise AttributeNotExist.new("Relation :#{name} names not existing attributes: #{attributes.join(", ")}", error.serializer, attributes)
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Serega
4
+ module SeregaValidations # :nodoc:
5
+ #
6
+ # Raises AttributeNotExist for the attributes that the field selection
7
+ # options name and the serializer does not have
8
+ #
9
+ class CheckSelection # :nodoc:
10
+ #
11
+ # Instantiates the field selection validator
12
+ #
13
+ def initialize
14
+ @parents_names = nil
15
+ @error_attributes = nil
16
+ end
17
+
18
+ # Validates provided fields names are existing attributes
19
+ def call(serializer_class, only, with, except)
20
+ validate(serializer_class, only)
21
+ validate(serializer_class, with)
22
+ validate(serializer_class, except)
23
+
24
+ raise_errors(serializer_class) if any_error?
25
+ end
26
+
27
+ private
28
+
29
+ def validate(serializer_class, fields)
30
+ fields.each do |name, nested_fields|
31
+ attribute = serializer_class && serializer_class.attributes[name]
32
+
33
+ # Save error when no attribute with checked name exists
34
+ unless attribute
35
+ save_error(name)
36
+ next
37
+ end
38
+
39
+ # Return when attribute has no nested fields
40
+ next if nested_fields.empty?
41
+
42
+ validate_nested(name, attribute, nested_fields)
43
+ end
44
+ end
45
+
46
+ # Validates the nested fields of an attribute with the attributes of
47
+ # its serializer
48
+ def validate_nested(name, attribute, nested_fields)
49
+ with_parent_name(name) do
50
+ validate(attribute.serializer, nested_fields)
51
+ end
52
+ end
53
+
54
+ def parents_names
55
+ @parents_names ||= []
56
+ end
57
+
58
+ def with_parent_name(name)
59
+ parents_names << name
60
+ yield
61
+ parents_names.pop
62
+ end
63
+
64
+ def error_attributes
65
+ @error_attributes ||= []
66
+ end
67
+
68
+ def save_error(name)
69
+ error_attributes << build_full_attribute_name(*parents_names, name)
70
+ end
71
+
72
+ def build_full_attribute_name(*names)
73
+ head, *nested = *names
74
+ result = +head.to_s # names are symbols, we need not frozen string
75
+ nested.each { |nested_name| result << "(" << nested_name.to_s }
76
+ nested.each { result << ")" }
77
+ result
78
+ end
79
+
80
+ def raise_errors(serializer_class)
81
+ raise Serega::AttributeNotExist.new("Not existing attributes: #{error_attributes.join(", ")}", serializer_class, error_attributes)
82
+ end
83
+
84
+ def any_error?
85
+ !@error_attributes.nil?
86
+ end
87
+ end
88
+ end
89
+ end
data/lib/serega.rb CHANGED
@@ -18,10 +18,10 @@ require_relative "serega/version"
18
18
  #
19
19
  # See the [guides](https://github.com/andreyruby/serega/blob/master/docs/README.md).
20
20
  class Serega
21
- # Frozen hash
21
+ # Frozen empty Hash, a shared default in place of a new `{}` per call
22
22
  FROZEN_EMPTY_HASH = {}.freeze # :nodoc:
23
23
 
24
- # Frozen array
24
+ # Frozen empty Array, a shared default in place of a new `[]` per call
25
25
  FROZEN_EMPTY_ARRAY = [].freeze # :nodoc:
26
26
 
27
27
  # Locks serializers one at a time
@@ -38,24 +38,32 @@ class Serega
38
38
  end
39
39
 
40
40
  require_relative "serega/errors"
41
+ require_relative "serega/utils/camel_case"
41
42
  require_relative "serega/utils/collection_detector"
42
43
  require_relative "serega/utils/deep_merge"
43
44
  require_relative "serega/utils/enum_deep_dup"
44
45
  require_relative "serega/utils/enum_deep_freeze"
45
46
  require_relative "serega/utils/method_signature"
46
- require_relative "serega/utils/parse_string_modifiers"
47
+ require_relative "serega/utils/parse_string_selection"
47
48
  require_relative "serega/utils/ractor_local"
49
+ require_relative "serega/utils/ruby_literal"
48
50
  require_relative "serega/utils/serialized_attribute_error"
49
51
  require_relative "serega/utils/to_hash"
52
+ require_relative "serega/attribute_value_resolvers/base"
50
53
  require_relative "serega/attribute_value_resolvers/batch"
54
+ require_relative "serega/attribute_value_resolvers/callable"
51
55
  require_relative "serega/attribute_value_resolvers/const"
52
56
  require_relative "serega/attribute_value_resolvers/delegate"
53
57
  require_relative "serega/attribute_value_resolvers/hash_access"
54
58
  require_relative "serega/attribute_value_resolvers/keyword"
55
59
  require_relative "serega/attribute_values"
56
60
  require_relative "serega/conditions"
57
- require_relative "serega/formatter"
61
+ require_relative "serega/formatters"
62
+ require_relative "serega/formatters/callable"
63
+ require_relative "serega/formatters/method"
58
64
  require_relative "serega/attribute"
65
+ require_relative "serega/attribute/serializer_reference"
66
+ require_relative "serega/attribute/value_code"
59
67
  require_relative "serega/attribute_normalizers/batch"
60
68
  require_relative "serega/attribute_normalizers/block"
61
69
  require_relative "serega/attribute_normalizers/delegate"
@@ -81,11 +89,16 @@ require_relative "serega/validations/attribute/check_opt_hash_access"
81
89
  require_relative "serega/validations/attribute/check_opt_many"
82
90
  require_relative "serega/validations/attribute/check_opt_method"
83
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"
84
94
  require_relative "serega/validations/attribute/check_opt_serializer"
85
95
  require_relative "serega/validations/attribute/check_opt_value"
86
- 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"
87
99
  require_relative "serega/validations/check_attribute_params"
88
100
  require_relative "serega/validations/check_batch_loader_params"
101
+ require_relative "serega/validations/check_preset_params"
89
102
  require_relative "serega/validations/check_formatter"
90
103
  require_relative "serega/validations/check_serialize_keywords"
91
104
 
@@ -93,10 +106,17 @@ require_relative "serega/batch_loader"
93
106
  require_relative "serega/config"
94
107
  require_relative "serega/presenter"
95
108
  require_relative "serega/source_group"
96
- require_relative "serega/plan_point"
97
109
  require_relative "serega/plan"
110
+ require_relative "serega/plan/depth_limit"
111
+ require_relative "serega/plan/point"
112
+ require_relative "serega/plan/selection"
98
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"
99
117
  require_relative "serega/result_builder"
118
+ require_relative "serega/plan/selection_planner"
119
+ require_relative "serega/plan/presets"
100
120
  require_relative "serega/plan/cache"
101
121
  require_relative "serega/plugins"
102
122
 
@@ -151,6 +171,18 @@ class Serega
151
171
  @attributes
152
172
  end
153
173
 
174
+ #
175
+ # Presets by name: the names of the presets each one includes and its
176
+ # own field selection
177
+ #
178
+ # ```ruby
179
+ # UserSerializer.presets # => {card: {presets: [], only: {posts: {title: {}}}, with: {}, except: {}}}
180
+ # ```
181
+ #
182
+ def presets
183
+ @presets
184
+ end
185
+
154
186
  # Lists defined batch loaders
155
187
  def batch_loaders # :nodoc:
156
188
  @batch_loaders
@@ -213,6 +245,8 @@ class Serega
213
245
  # attribute :name, method: :full_name
214
246
  # attribute :email, hide: true
215
247
  # attribute :posts, serializer: PostSerializer
248
+ # attribute :posts, serializer: PostSerializer, preset: :summary # fields of a preset
249
+ # attribute :posts, serializer: PostSerializer, only: [:id, :title]
216
250
  # ```
217
251
  #
218
252
  # A block defines the attributes of a nested serializer. It inherits from
@@ -235,6 +269,31 @@ class Serega
235
269
  attributes[attribute.name] = attribute
236
270
  end
237
271
 
272
+ #
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.
277
+ #
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.
281
+ #
282
+ # ```ruby
283
+ # preset :card, only: [:first_name, {avatar: :url}]
284
+ # preset :profile, preset: :card, with: {posts: :comments}
285
+ #
286
+ # UserSerializer.to_h(user, preset: :profile, except: :avatar)
287
+ # ```
288
+ #
289
+ # See [Presets](https://github.com/andreyruby/serega/blob/master/docs/selecting-fields.md#presets).
290
+ #
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
+
238
297
  #
239
298
  # Defines a named batch loader: a callable or a block that receives the
240
299
  # objects, and the context as a second parameter or as the `:ctx`
@@ -282,7 +341,7 @@ class Serega
282
341
 
283
342
  value ||= block
284
343
  SeregaValidations::CheckFormatter.call(name, value)
285
- formatters[name] = SeregaFormatter.new({use: value, allow_nil: allow_nil})
344
+ formatters[name] = SeregaFormatters.build({use: value, allow_nil: allow_nil})
286
345
  end
287
346
 
288
347
  #
@@ -325,17 +384,20 @@ class Serega
325
384
  #
326
385
  # See [Preloads](https://github.com/andreyruby/serega/blob/master/docs/preloads.md).
327
386
  #
328
- def preload_with(value = nil, &block)
329
- return @preload_with if value.nil? && block.nil?
387
+ def preload_with(value = (omitted = true), &block)
388
+ return @preload_with_handler if omitted && block.nil?
330
389
 
331
390
  check_unlocked
332
- handler = checked_handler(:preload_with, value, block)
391
+ handler = omitted ? block : checked_value_handler(:preload_with, value, block)
333
392
  signature = SeregaUtils::MethodSignature.call(handler, pos_limit: 2)
334
393
  raise SeregaError, "preload_with handler must accept two positional arguments: (objects, preloads)" unless signature == "2"
335
394
 
336
- @preload_with = handler
395
+ @preload_with_handler = handler
337
396
  end
338
397
 
398
+ # The handler registered with `preload_with`
399
+ attr_reader :preload_with_handler # :nodoc:
400
+
339
401
  #
340
402
  # Sets the handler that replaces the objects given to the serializer, for
341
403
  # example ids with records. It runs once per serialization, before Serega
@@ -351,18 +413,21 @@ class Serega
351
413
  #
352
414
  # See [Prepare initial objects](https://github.com/andreyruby/serega/blob/master/docs/prepare-initial-objects.md).
353
415
  #
354
- def prepare_initial_objects(value = nil, &block)
355
- return @prepare_initial_objects if value.nil? && block.nil?
416
+ def prepare_initial_objects(value = (omitted = true), &block)
417
+ return @prepare_initial_objects_handler if omitted && block.nil?
356
418
 
357
419
  check_unlocked
358
- handler = checked_handler(:prepare_initial_objects, value, block)
420
+ handler = omitted ? block : checked_value_handler(:prepare_initial_objects, value, block)
359
421
  signature = SeregaUtils::MethodSignature.call(handler, pos_limit: 2, keyword_args: [:ctx])
360
422
  raise SeregaError, prepare_initial_objects_signature_error unless %w[1 2 1_ctx].include?(signature)
361
423
 
362
424
  @prepare_initial_objects_signature = signature
363
- @prepare_initial_objects = handler
425
+ @prepare_initial_objects_handler = handler
364
426
  end
365
427
 
428
+ # The handler registered with `prepare_initial_objects`
429
+ attr_reader :prepare_initial_objects_handler # :nodoc:
430
+
366
431
  # Signature of the registered prepare_initial_objects handler
367
432
  attr_reader :prepare_initial_objects_signature # :nodoc:
368
433
 
@@ -375,8 +440,8 @@ class Serega
375
440
  #
376
441
  # - `only`, `except`, `with`: fields to serialize, to skip and to add,
377
442
  # see [Selecting fields](https://github.com/andreyruby/serega/blob/master/docs/selecting-fields.md);
378
- # - `check_initiate_params`: `false` skips unknown fields, by default
379
- # `config.check_initiate_params`;
443
+ # - `check_selection`: `false` skips unknown fields, by default
444
+ # `config.check_selection`;
380
445
  # - `context`: data for attribute values and conditions;
381
446
  # - `many`: `true` serializes a list, `false` one object. By default an
382
447
  # `Enumerable` that is not a `Hash` or `Struct` is a list.
@@ -389,8 +454,10 @@ class Serega
389
454
  #
390
455
  # See [Serializing](https://github.com/andreyruby/serega/blob/master/docs/serializing.md).
391
456
  #
392
- def call(object, only: nil, with: nil, except: nil, check_initiate_params: nil, context: nil, many: nil)
393
- new(only: only, with: with, except: except, check_initiate_params: check_initiate_params)
457
+ def call(object, only: nil, with: nil, except: nil, preset: nil, check_selection: nil, context: nil, many: nil)
458
+ # The serialization methods list each keyword instead of taking
459
+ # `**opts`: a `**opts` Hash allocates on every call, even when empty.
460
+ new(only: only, with: with, except: except, preset: preset, check_selection: check_selection)
394
461
  .to_h(object, context: context, many: many)
395
462
  end
396
463
 
@@ -404,8 +471,8 @@ class Serega
404
471
  # UserSerializer.to_data(user) # => #<data first_name="Bruce">
405
472
  # ```
406
473
  #
407
- def to_data(object, only: nil, with: nil, except: nil, check_initiate_params: nil, context: nil, many: nil)
408
- new(only: only, with: with, except: except, check_initiate_params: check_initiate_params)
474
+ def to_data(object, only: nil, with: nil, except: nil, preset: nil, check_selection: nil, context: nil, many: nil)
475
+ new(only: only, with: with, except: except, preset: preset, check_selection: check_selection)
409
476
  .to_data(object, context: context, many: many)
410
477
  end
411
478
 
@@ -419,8 +486,8 @@ class Serega
419
486
  # UserSerializer.to_struct(user) # => #<struct first_name="Bruce">
420
487
  # ```
421
488
  #
422
- def to_struct(object, only: nil, with: nil, except: nil, check_initiate_params: nil, context: nil, many: nil)
423
- new(only: only, with: with, except: except, check_initiate_params: check_initiate_params)
489
+ def to_struct(object, only: nil, with: nil, except: nil, preset: nil, check_selection: nil, context: nil, many: nil)
490
+ new(only: only, with: with, except: except, preset: preset, check_selection: check_selection)
424
491
  .to_struct(object, context: context, many: many)
425
492
  end
426
493
 
@@ -435,8 +502,8 @@ class Serega
435
502
  # UserSerializer.to_json(user) # => "{\"first_name\":\"Bruce\"}"
436
503
  # ```
437
504
  #
438
- def to_json(object, only: nil, with: nil, except: nil, check_initiate_params: nil, context: nil, many: nil)
439
- new(only: only, with: with, except: except, check_initiate_params: check_initiate_params)
505
+ def to_json(object, only: nil, with: nil, except: nil, preset: nil, check_selection: nil, context: nil, many: nil)
506
+ new(only: only, with: with, except: except, preset: preset, check_selection: check_selection)
440
507
  .to_json(object, context: context, many: many)
441
508
  end
442
509
 
@@ -451,7 +518,10 @@ class Serega
451
518
  next if @locked
452
519
 
453
520
  SeregaUtils::EnumDeepFreeze.call(config.opts)
454
- define_presenter_delegators if @presenter_class
521
+ if @presenter_class
522
+ define_presenter_delegators
523
+ attributes.each_value { |attribute| attribute.check_presenter(@presenter_class) }
524
+ end
455
525
  @locked = true
456
526
  end
457
527
  end
@@ -489,7 +559,7 @@ class Serega
489
559
  @presenter_key = SeregaUtils::RactorLocal.key(self, :presenter)
490
560
  end
491
561
  @unshareable_reason = SeregaShareable.call(self)
492
- @plan_cache = SeregaPlan::PerRactorCache.new(self) unless @unshareable_reason
562
+ @plan_cache = SeregaPlan::PerRactorCache.new(self, SeregaPlan::SelectionPlanner) unless @unshareable_reason
493
563
  end
494
564
  # :nocov:
495
565
  self
@@ -533,11 +603,14 @@ class Serega
533
603
  subclass.attributes[subclass_attribute.name] = subclass_attribute
534
604
  end
535
605
 
606
+ # Assign same presets
607
+ subclass.presets.merge!(presets)
608
+
536
609
  # Assign same preload handler
537
- subclass.preload_with(preload_with) if preload_with
610
+ subclass.preload_with(preload_with_handler) if preload_with_handler
538
611
 
539
612
  # Assign same initial objects handler
540
- subclass.prepare_initial_objects(prepare_initial_objects) if prepare_initial_objects
613
+ subclass.prepare_initial_objects(prepare_initial_objects_handler) if prepare_initial_objects_handler
541
614
 
542
615
  # Assign same presenter blocks
543
616
  presenter_blocks.each do |presenter_block|
@@ -553,6 +626,7 @@ class Serega
553
626
  def initialize_definition(config, formatters)
554
627
  @config = config
555
628
  @attributes = {}
629
+ @presets = {}
556
630
  @batch_loaders = {}
557
631
  @formatters = formatters
558
632
  @presenter_class = nil
@@ -560,23 +634,21 @@ class Serega
560
634
  @presenter_key = nil
561
635
  @data_classes = {}
562
636
  @struct_classes = {}
563
- @preload_with = nil
564
- @prepare_initial_objects = nil
637
+ @preload_with_handler = nil
638
+ @prepare_initial_objects_handler = nil
565
639
  @prepare_initial_objects_signature = nil
566
640
  @locked = false
567
641
  @shareable = false
568
642
  @unshareable_reason = nil
569
- @plan_cache = SeregaPlan::Cache.new(self)
643
+ @plan_cache = SeregaPlan::Cache.new(self, SeregaPlan::SelectionPlanner)
570
644
  end
571
645
 
572
- # The handler given to `method_name` as a value or a block
573
- def checked_handler(method_name, value, block)
574
- raise SeregaError, "#{method_name} accepts a single callable or a block, not both" if value && block
646
+ # The handler given to `method_name` as a value, which must come without a block
647
+ def checked_value_handler(method_name, value, block)
648
+ raise SeregaError, "#{method_name} accepts a single callable or a block, not both" if block
649
+ raise SeregaError, "#{method_name} value must be a Proc or respond to #call" unless value.respond_to?(:call)
575
650
 
576
- handler = value || block
577
- raise SeregaError, "#{method_name} value must be a Proc or respond to #call" unless handler.respond_to?(:call)
578
-
579
- handler
651
+ value
580
652
  end
581
653
 
582
654
  def prepare_initial_objects_signature_error
@@ -604,10 +676,8 @@ class Serega
604
676
  # serializer.to_h(users) # => [{first_name: "Bruce"}, {first_name: "Alfred"}]
605
677
  # ```
606
678
  #
607
- def initialize(only: nil, with: nil, except: nil, check_initiate_params: nil)
608
- modifiers = !(only.nil? && with.nil? && except.nil?)
609
- check_initiate_params = config.check_initiate_params if modifiers && check_initiate_params.nil?
610
- @plan = self.class.plan_cache.fetch(only, with, except, check_initiate_params: modifiers && check_initiate_params)
679
+ def initialize(only: nil, with: nil, except: nil, preset: nil, check_selection: nil)
680
+ @plan = self.class.plan_cache.fetch(only, with, except, preset, check_selection: check_selection)
611
681
  @direct_hash_builder = @plan.direct_hash_builder
612
682
  end
613
683
 
@@ -627,9 +697,11 @@ class Serega
627
697
  # ```
628
698
  #
629
699
  def call(object, context: nil, many: nil)
700
+ # One Hash source of a flat plan skips #serialize_to and the run: 73 ns
701
+ # and 1 object instead of 136 ns and 3 objects (Ruby 4.0, YJIT).
630
702
  builder = @direct_hash_builder
631
703
  if builder && object && !many && (context.nil? || context.is_a?(Hash))
632
- many = SeregaUtils::CollectionDetector.call(object, @plan.collection_classes) if many.nil?
704
+ many = object.instance_of?(Array) || SeregaUtils::CollectionDetector.call(object, @plan.collection_classes) if many.nil?
633
705
  return builder.call_one(object, context.nil? ? FROZEN_EMPTY_HASH : context) unless many
634
706
  end
635
707
 
@@ -671,22 +743,18 @@ class Serega
671
743
 
672
744
  private
673
745
 
674
- def config
675
- self.class.config
676
- end
677
-
678
746
  # Serializes the object with the serialization options. `opts` holds the
679
747
  # options other than :context and :many.
680
748
  def serialize_to(mode, object, context, many, opts)
681
749
  SeregaValidations::CheckSerializeKeywords.call(context, many)
682
750
  context ||= FROZEN_EMPTY_HASH
683
751
  object = prepare_objects(object, context) if self.class.prepare_initial_objects_signature
684
- many = SeregaUtils::CollectionDetector.call(object, @plan.collection_classes) if many.nil?
752
+ many = object.instance_of?(Array) || SeregaUtils::CollectionDetector.call(object, @plan.collection_classes) if many.nil?
685
753
  serialize(object, opts, context, many, mode)
686
754
  end
687
755
 
688
756
  def prepare_objects(objects, context)
689
- handler = self.class.prepare_initial_objects
757
+ handler = self.class.prepare_initial_objects_handler
690
758
 
691
759
  case self.class.prepare_initial_objects_signature
692
760
  when "1" then handler.call(objects)
data/sig/serega.rbs CHANGED
@@ -4,6 +4,12 @@ class Serega
4
4
  # Fields of the `only:`, `except:` and `with:` options
5
5
  type fields = Symbol | String | Array[fields] | Hash[Symbol | String, fields]
6
6
 
7
+ # Names of the `preset:` option
8
+ type preset_names = Symbol | String | Array[Symbol | String]
9
+
10
+ # Definition of a preset: the presets it includes and its own field selection
11
+ type preset_definition = { presets: Array[Symbol], only: Hash[Symbol, untyped], with: Hash[Symbol, untyped], except: Hash[Symbol, untyped] }
12
+
7
13
  # Serialization context
8
14
  type context = Hash[untyped, untyped]
9
15
 
@@ -19,6 +25,10 @@ class Serega
19
25
 
20
26
  def attribute: (Symbol | String name, **untyped opts) ?{ () [self: singleton(Serega)] -> void } -> SeregaAttribute
21
27
 
28
+ def presets: () -> Hash[Symbol, preset_definition]
29
+
30
+ def preset: (Symbol | String name, ?preset: preset_names?, ?only: fields?, ?with: fields?, ?except: fields?) -> preset_definition
31
+
22
32
  def batch: (Symbol | String name, untyped loader) -> void
23
33
  | (Symbol | String name) { (untyped objects) -> untyped } -> void
24
34
  | (Symbol | String name) { (untyped objects, context context) -> untyped } -> void
@@ -44,17 +54,17 @@ class Serega
44
54
 
45
55
  # Results are `untyped`: plugins change their shape. Options that plugins
46
56
  # add at load time, such as `root:`, are not in these signatures.
47
- def call: (untyped object, ?only: fields?, ?with: fields?, ?except: fields?, ?check_initiate_params: bool?, ?context: context?, ?many: bool?) -> untyped
57
+ def call: (untyped object, ?only: fields?, ?with: fields?, ?except: fields?, ?preset: preset_names?, ?check_selection: bool?, ?context: context?, ?many: bool?) -> untyped
48
58
  alias to_h call
49
- def to_data: (untyped object, ?only: fields?, ?with: fields?, ?except: fields?, ?check_initiate_params: bool?, ?context: context?, ?many: bool?) -> untyped
50
- def to_struct: (untyped object, ?only: fields?, ?with: fields?, ?except: fields?, ?check_initiate_params: bool?, ?context: context?, ?many: bool?) -> untyped
51
- def to_json: (untyped object, ?only: fields?, ?with: fields?, ?except: fields?, ?check_initiate_params: bool?, ?context: context?, ?many: bool?) -> String
59
+ def to_data: (untyped object, ?only: fields?, ?with: fields?, ?except: fields?, ?preset: preset_names?, ?check_selection: bool?, ?context: context?, ?many: bool?) -> untyped
60
+ def to_struct: (untyped object, ?only: fields?, ?with: fields?, ?except: fields?, ?preset: preset_names?, ?check_selection: bool?, ?context: context?, ?many: bool?) -> untyped
61
+ def to_json: (untyped object, ?only: fields?, ?with: fields?, ?except: fields?, ?preset: preset_names?, ?check_selection: bool?, ?context: context?, ?many: bool?) -> String
52
62
 
53
63
  def make_shareable!: () -> self
54
64
  end
55
65
 
56
66
  module InstanceMethods
57
- def initialize: (?only: fields?, ?with: fields?, ?except: fields?, ?check_initiate_params: bool?) -> void
67
+ def initialize: (?only: fields?, ?with: fields?, ?except: fields?, ?preset: preset_names?, ?check_selection: bool?) -> void
58
68
 
59
69
  def call: (untyped object, ?context: context?, ?many: bool?) -> untyped
60
70
  alias to_h call
@@ -93,8 +103,8 @@ class Serega
93
103
  include SeregaConfigInstanceMethods
94
104
 
95
105
  module SeregaConfigInstanceMethods
96
- def check_initiate_params: () -> bool
97
- def check_initiate_params=: (bool value) -> bool
106
+ def check_selection: () -> bool
107
+ def check_selection=: (bool value) -> bool
98
108
 
99
109
  def check_attribute_name: () -> bool
100
110
  def check_attribute_name=: (bool value) -> bool
@@ -105,6 +115,12 @@ class Serega
105
115
  def delegate_default_allow_nil: () -> bool
106
116
  def delegate_default_allow_nil=: (bool value) -> bool
107
117
 
118
+ def compact: () -> bool
119
+ def compact=: (bool value) -> bool
120
+
121
+ def key_transform: () -> (:camel_case | ^(Symbol) -> (Symbol | String) | nil)
122
+ def key_transform=: (:camel_case | ^(Symbol) -> (Symbol | String) | nil value) -> (:camel_case | ^(Symbol) -> (Symbol | String) | nil)
123
+
108
124
  def hide_by_default: () -> (bool | :auto)
109
125
  def hide_by_default=: (bool | :auto value) -> (bool | :auto)
110
126