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
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Serega
4
+ module SeregaFormatters # :nodoc:
5
+ #
6
+ # Formatter that calls a callable with the value, and with the context
7
+ # when the callable takes it
8
+ #
9
+ class Callable # :nodoc:
10
+ # Callable that formats a value
11
+ attr_reader :callable
12
+
13
+ def initialize(callable, allow_nil)
14
+ @callable = callable
15
+ @signature = SeregaUtils::MethodSignature.call(callable, pos_limit: 2, keyword_args: [:ctx])
16
+ @allow_nil = allow_nil
17
+ end
18
+
19
+ # A callable formatter has no method arguments
20
+ def args
21
+ end
22
+
23
+ # Formats the value
24
+ def call(value, context)
25
+ return if value.nil? && @allow_nil
26
+
27
+ case @signature
28
+ when "1" then @callable.call(value)
29
+ when "1_ctx" then @callable.call(value, ctx: context)
30
+ else @callable.call(value, context) # "2"
31
+ end
32
+ end
33
+
34
+ # Ruby code that calls the callable that `callable_code` reads with the
35
+ # value of `value_code`. A callable that takes the context has no code.
36
+ def code(value_code, callable_code, _args_code)
37
+ return unless @signature == "1"
38
+ return "#{callable_code}.call(#{value_code})" unless @allow_nil
39
+
40
+ "(value = #{value_code}).nil? ? nil : #{callable_code}.call(value)"
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Serega
4
+ module SeregaFormatters # :nodoc:
5
+ #
6
+ # Formatter that calls a method of the value, for example `[:round, 2]`
7
+ #
8
+ class Method # :nodoc:
9
+ # Arguments of the method
10
+ attr_reader :args
11
+
12
+ def initialize(use, allow_nil)
13
+ method_name, *args = use
14
+ @method_name = method_name
15
+ @args = args
16
+ @allow_nil = allow_nil
17
+ end
18
+
19
+ # A method formatter has no callable
20
+ def callable
21
+ end
22
+
23
+ # Formats the value
24
+ def call(value, _context)
25
+ return if value.nil? && @allow_nil
26
+
27
+ value.public_send(@method_name, *@args)
28
+ end
29
+
30
+ # Ruby code that calls the method on the value of `value_code`, for
31
+ # example `(source.created_at).iso8601(3)`. Literal arguments are
32
+ # written in the code, other arguments are read from the Array that
33
+ # `args_code` reads.
34
+ def code(value_code, _callable_code, args_code)
35
+ operator = @allow_nil ? "&." : "."
36
+ arguments = @args.each_with_index.map { |arg, index| argument_code(arg, index, args_code) }
37
+
38
+ unless SeregaResultCode::PLAIN_METHOD_NAME.match?(@method_name)
39
+ send_arguments = [@method_name.inspect, *arguments]
40
+ return "(#{value_code})#{operator}public_send(#{send_arguments.join(", ")})"
41
+ end
42
+
43
+ return "(#{value_code})#{operator}#{@method_name}" if arguments.empty?
44
+
45
+ "(#{value_code})#{operator}#{@method_name}(#{arguments.join(", ")})"
46
+ end
47
+
48
+ private
49
+
50
+ def argument_code(arg, index, args_code)
51
+ SeregaUtils::RubyLiteral.literal?(arg) ? SeregaUtils::RubyLiteral.code(arg) : "#{args_code}[#{index}]"
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Serega
4
+ #
5
+ # Formatters of attribute values. A formatter declaration is one of:
6
+ # - a callable that gets the value, and the context when it has a second
7
+ # parameter or the :ctx keyword;
8
+ # - a method name, called on the value;
9
+ # - an Array of a method name and its arguments, for example `[:round, 2]`;
10
+ # - a Hash with one of them as `:use` and the `:allow_nil` option.
11
+ #
12
+ # With `allow_nil: true` a nil value stays nil and is not formatted.
13
+ #
14
+ module SeregaFormatters # :nodoc:
15
+ class << self
16
+ # Returns the formatter of the declaration: a Callable for a callable,
17
+ # a Method for a method name with its arguments
18
+ def build(declaration)
19
+ declaration = {use: declaration} unless declaration.is_a?(Hash)
20
+ use = declaration[:use]
21
+ allow_nil = declaration.fetch(:allow_nil, false)
22
+
23
+ use.respond_to?(:call) ? Callable.new(use, allow_nil) : Method.new(use, allow_nil)
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,119 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Serega
4
+ class SeregaPlan # :nodoc:
5
+ #
6
+ # Serialization plans of one serializer, cached by up to four
7
+ # parameters, such as the `only`, `with` and `except` field selection
8
+ # options and the `preset`. The planner parses and validates the parameters and builds
9
+ # the plans.
10
+ #
11
+ class Cache # :nodoc:
12
+ # Cached plan, whether its parameters were validated, and the
13
+ # parameters as provided
14
+ CACHED_PLAN = Struct.new(:plan, :validated, :param1, :param2, :param3, :param4) do
15
+ # Whether the given parameters equal the cached ones
16
+ def same_params?(param1, param2, param3, param4)
17
+ param1.eql?(self.param1) && param2.eql?(self.param2) && param3.eql?(self.param3) && param4.eql?(self.param4)
18
+ end
19
+
20
+ # Validates the cached parameters with the planner, once
21
+ def validate(planner, serializer_class)
22
+ return if validated
23
+
24
+ planner.validate(serializer_class, planner.parse(serializer_class, param1, param2, param3, param4))
25
+ self.validated = true
26
+ end
27
+ end
28
+ private_constant :CACHED_PLAN
29
+
30
+ # Initializes empty plans cache of the serializer with the planner of
31
+ # its parameters
32
+ def initialize(serializer_class, planner)
33
+ @serializer_class = serializer_class
34
+ @planner = planner
35
+ @default_plan = nil
36
+ @plans = {}
37
+ end
38
+
39
+ # Returns serialization plan for provided parameters. The planner gives
40
+ # them their meaning, for example `only`, `with`, `except` and `preset`; a planner
41
+ # with fewer parameters leaves the last ones out. They are separate
42
+ # arguments, not an Array: an Array, a splat or a Struct allocates on
43
+ # every `Serega.new`, which adds 13 to 36 ns to a cached `Serega.new`
44
+ # of about 114 ns.
45
+ #
46
+ # The plan without parameters is always cached; plans with parameters
47
+ # are cached by parameters as provided when
48
+ # `max_cached_plans_per_serializer_count` is positive. Parameters are
49
+ # parsed when a plan is built, and validated when
50
+ # `check_selection` is true, or nil with
51
+ # `config.check_selection` on.
52
+ def fetch(param1 = nil, param2 = nil, param3 = nil, param4 = nil, check_selection: nil)
53
+ return default_plan if param1.nil? && param2.nil? && param3.nil? && param4.nil?
54
+
55
+ config = @serializer_class.config
56
+ check_selection = config.check_selection if check_selection.nil?
57
+ max_size = config.max_cached_plans_per_serializer_count
58
+ return build(param1, param2, param3, param4, check_selection) if max_size.zero?
59
+
60
+ cached_plan(param1, param2, param3, param4, max_size, check_selection)
61
+ end
62
+
63
+ private
64
+
65
+ # The plan without parameters, built by the planner from no parameters
66
+ def default_plan
67
+ @default_plan ||= @planner.plan(@serializer_class, @planner.parse(@serializer_class))
68
+ end
69
+
70
+ # Keeps plans by the key of the parameters, and compares each
71
+ # parameter with the cached one. Parameters with the key of other
72
+ # cached parameters replace them.
73
+ def cached_plan(param1, param2, param3, param4, max_size, check_selection)
74
+ key = cache_key(param1, param2, param3, param4)
75
+ cached = @plans[key]
76
+ if cached&.same_params?(param1, param2, param3, param4)
77
+ cached.validate(@planner, @serializer_class) if check_selection
78
+ return cached.plan
79
+ end
80
+
81
+ plan = build(param1, param2, param3, param4, check_selection)
82
+ @plans[key] = CACHED_PLAN.new(plan, check_selection, *frozen_copy([param1, param2, param3, param4]))
83
+ @plans.shift if @plans.length > max_size
84
+ plan
85
+ end
86
+
87
+ # The hash of the hash values of the parameters: an Array of the
88
+ # parameters as the key hashes and compares nested arrays inside a
89
+ # recursion guard. A lone parameter is keyed by its own hash, salted by
90
+ # its position, so `only: x`, `with: x`, `except: x` and `preset: x`
91
+ # have different keys. It skips the Array and takes 11% off a cached
92
+ # `Serega.new` with one option or preset. A missing fourth parameter
93
+ # stays out of the Array: the longer Array adds about 4 ns.
94
+ def cache_key(param1, param2, param3, param4)
95
+ # rubocop:disable Security/CompoundHash -- `[param1, param2, param3].hash` hashes nested arrays inside a recursion guard
96
+ if param2.nil? && param3.nil? && param4.nil? then param1.hash ^ 0 # salt 0
97
+ elsif param1.nil? && param3.nil? && param4.nil? then param2.hash ^ 1 # salt 1
98
+ elsif param1.nil? && param2.nil? && param4.nil? then param3.hash ^ 2 # salt 2
99
+ elsif param1.nil? && param2.nil? && param3.nil? then param4.hash ^ 3 # salt 3
100
+ elsif param4.nil? then [param1.hash, param2.hash, param3.hash].hash
101
+ else [param1.hash, param2.hash, param3.hash, param4.hash].hash
102
+ end
103
+ # rubocop:enable Security/CompoundHash
104
+ end
105
+
106
+ def build(param1, param2, param3, param4, check_selection)
107
+ params = @planner.parse(@serializer_class, param1, param2, param3, param4)
108
+ return default_plan if @planner.empty?(params)
109
+
110
+ @planner.validate(@serializer_class, params) if check_selection
111
+ @planner.plan(@serializer_class, params)
112
+ end
113
+
114
+ def frozen_copy(params)
115
+ SeregaUtils::EnumDeepFreeze.call(SeregaUtils::EnumDeepDup.call(params))
116
+ end
117
+ end
118
+ end
119
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Serega
4
+ class SeregaPlan # :nodoc:
5
+ #
6
+ # Depth limit of plans: the levels of child plans that `config.depth_limit`
7
+ # of the root serializer allows below a plan.
8
+ #
9
+ module DepthLimit # :nodoc:
10
+ class << self
11
+ # Depth left below a plan: the depth limit of the serializer for a
12
+ # root plan, one level less than the parent plan's for a child plan,
13
+ # `nil` without a limit. Raises DepthLimitError when the parent plan
14
+ # has no level left.
15
+ def depth_left(serializer_class, parent_plan_point)
16
+ return serializer_class.config.depth_limit unless parent_plan_point
17
+
18
+ parent_depth_left = parent_plan_point.plan.depth_left
19
+ return unless parent_depth_left
20
+ return parent_depth_left - 1 if parent_depth_left > 1
21
+
22
+ raise_depth_limit_error(parent_plan_point)
23
+ end
24
+
25
+ private
26
+
27
+ def raise_depth_limit_error(parent_plan_point)
28
+ root_serializer = parent_plan_point.plan.root_plan.serializer_class
29
+ limit = root_serializer.config.depth_limit
30
+ path = parent_plan_point.path.join(" -> ")
31
+ raise DepthLimitError.new("Depth limit was exceeded", "#{root_serializer} (depth limit: #{limit}) -> #{path}\n(hint: if the nesting is not a cycle, increase config.depth_limit of #{root_serializer})")
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Serega
4
+ class SeregaPlan # :nodoc:
5
+ #
6
+ # Shareable plans cache of a shareable serializer, keeps the plans of each
7
+ # Ractor apart
8
+ #
9
+ class PerRactorCache # :nodoc:
10
+ # Keeps the plans of the serializer with the planner in a Cache per
11
+ # Ractor, under a key of the serializer and the planner
12
+ def initialize(serializer_class, planner)
13
+ @serializer_class = serializer_class
14
+ @planner = planner
15
+ @key = SeregaUtils::RactorLocal.key(serializer_class, "plan_cache_#{planner.object_id}")
16
+ freeze
17
+ end
18
+
19
+ # Returns serialization plan from the plans cache of the current Ractor.
20
+ # Takes the parameters one by one like Cache#fetch: a splat allocates
21
+ # an Array on every `Serega.new`.
22
+ def fetch(param1 = nil, param2 = nil, param3 = nil, param4 = nil, check_selection: nil)
23
+ plan_cache = SeregaUtils::RactorLocal.fetch(@key) { SeregaPlan::Cache.new(@serializer_class, @planner) }
24
+ plan_cache.fetch(param1, param2, param3, param4, check_selection: check_selection)
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Serega
4
+ class SeregaPlan # :nodoc:
5
+ #
6
+ # One attribute in a plan, with the child plan of a relation
7
+ #
8
+ class Point # :nodoc:
9
+ # Link to current plan this point belongs to
10
+ attr_reader :plan
11
+
12
+ # Shows current attribute
13
+ attr_reader :attribute
14
+
15
+ # Attribute `name`
16
+ attr_reader :name
17
+
18
+ # Attribute `key`, the key of the serialized Hash
19
+ attr_reader :key
20
+
21
+ # Preloads of the point, given by the selection
22
+ attr_reader :preloads
23
+
24
+ # Shows child plan if exists
25
+ attr_reader :child_plan
26
+
27
+ # Whether the relation values of a class are collections, for a point
28
+ # with a child plan
29
+ attr_reader :collection_classes
30
+
31
+ # Initializes plan point. A point with a child selection gets a child
32
+ # plan of it.
33
+ def initialize(plan, attribute, preloads, child_selection)
34
+ @plan = plan
35
+ @attribute = attribute
36
+ @name = attribute.name
37
+ @key = attribute.key
38
+ @preloads = preloads
39
+ @child_plan = child_selection ? SeregaPlan.new(child_selection, self) : nil
40
+ @collection_classes = @child_plan ? {}.compare_by_identity : nil
41
+ end
42
+
43
+ # Attribute names from the root plan down to this point
44
+ def path
45
+ names = [name]
46
+ point = self
47
+ names.unshift(point.name) while (point = point.plan.parent_plan_point)
48
+ names
49
+ end
50
+
51
+ # Attribute `many` option
52
+ def many
53
+ attribute.many
54
+ end
55
+
56
+ # Attribute `batch_loaders`
57
+ def batch_loaders
58
+ attribute.batch_loaders
59
+ end
60
+
61
+ # Attribute `conditional?`
62
+ def conditional?
63
+ attribute.conditional?
64
+ end
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Serega
4
+ class SeregaPlan # :nodoc:
5
+ #
6
+ # Presets: named field selections. The serializer calls it to define its
7
+ # presets, and the selection planner to merge the requested presets with
8
+ # the selection of a call.
9
+ #
10
+ module Presets # :nodoc:
11
+ class << self
12
+ # Returns the frozen definition of a new preset: the names of the
13
+ # presets it includes and its own parsed selection. The included
14
+ # presets are merged when a plan is built, thus a redefined preset
15
+ # changes the presets that include it. See
16
+ # SeregaValidations::CheckPresetParams for the checks.
17
+ def define(serializer_class, name, preset, only, with, except)
18
+ SeregaValidations::CheckPresetParams.new(serializer_class, name, preset, only, with, except).validate
19
+ definition(preset, only, with, except)
20
+ end
21
+
22
+ # Returns a frozen preset definition of checked options: the names
23
+ # of the included presets and the parsed selection. A relation keeps
24
+ # its `preset`, `only`, `with` and `except` options in one.
25
+ def definition(preset, only, with, except)
26
+ names = preset.nil? ? FROZEN_EMPTY_ARRAY : names(preset)
27
+ definition = {presets: names, only: SelectionPlanner.parse_option(only), with: SelectionPlanner.parse_option(with), except: SelectionPlanner.parse_option(except)}
28
+ deep_freeze(definition)
29
+ end
30
+
31
+ # Returns the selection of the requested presets, merged in order,
32
+ # with the given parsed selection merged into it. Presets are
33
+ # checked when they are defined, not here.
34
+ def selection(serializer_class, preset, selection)
35
+ merge(merged_selection(serializer_class, names(preset)), selection)
36
+ end
37
+
38
+ # Returns the selection of a relation: the selection of the preset
39
+ # definition of the attribute, with the given parsed selection
40
+ # merged into it. Checks the definition of a relation serializer that
41
+ # was resolved later, see SeregaValidations::CheckRelationSelection.
42
+ def relation_selection(attribute, selection)
43
+ serializer = attribute.serializer
44
+ SeregaValidations::CheckRelationSelection.call(attribute, serializer)
45
+
46
+ definition = attribute.selection
47
+ merge(merge(merged_selection(serializer, definition[:presets]), definition), selection)
48
+ end
49
+
50
+ # Returns the definition of the preset, raises PresetNotExist for an
51
+ # undefined preset
52
+ def fetch_definition(serializer_class, name)
53
+ serializer_class.presets.fetch(name) do
54
+ raise PresetNotExist.new("Preset :#{name} is not defined in #{serializer_class}", serializer_class, name)
55
+ end
56
+ end
57
+
58
+ # Returns the preset names of a `preset:` option as an Array of
59
+ # Symbols, raises SeregaError for another value
60
+ def names(preset)
61
+ case preset
62
+ when Symbol then [preset]
63
+ when String then [preset.to_sym]
64
+ when Array then preset.map { |name| name_of(name, preset) }
65
+ else raise_option_error(preset)
66
+ end
67
+ end
68
+
69
+ private
70
+
71
+ # Merges each option of `other` into the option of `selection` with
72
+ # the same name, and skips a nil option. Nested Hashes merge into new
73
+ # Hashes, thus the frozen selections of presets stay unchanged.
74
+ def merge(selection, other)
75
+ selection.each_key do |key|
76
+ option = other[key]
77
+ SeregaUtils::DeepMerge.call(selection[key], option) if option
78
+ end
79
+ selection
80
+ end
81
+
82
+ # Merges the selection of the named presets and of the presets they
83
+ # include into `selection`, the included presets first. Presets never
84
+ # include each other: #define checks it.
85
+ def merged_selection(serializer_class, names, selection = {only: {}, with: {}, except: {}})
86
+ names.each do |name|
87
+ definition = fetch_definition(serializer_class, name)
88
+ merged_selection(serializer_class, definition[:presets], selection)
89
+ merge(selection, definition)
90
+ end
91
+ selection
92
+ end
93
+
94
+ def name_of(name, preset)
95
+ case name
96
+ when Symbol then name
97
+ when String then name.to_sym
98
+ else raise_option_error(preset)
99
+ end
100
+ end
101
+
102
+ def raise_option_error(preset)
103
+ raise SeregaError, "Invalid option :preset => #{preset.inspect}. Must be a Symbol, a String, or an Array of them"
104
+ end
105
+
106
+ # Freezes the nested Hashes and Arrays of a preset definition
107
+ def deep_freeze(value)
108
+ return value if value.frozen?
109
+
110
+ value.each_value { |nested_value| deep_freeze(nested_value) } if value.is_a?(Hash)
111
+ value.freeze
112
+ end
113
+ end
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Serega
4
+ class SeregaPlan # :nodoc:
5
+ #
6
+ # The attributes a plan serializes, selected with the parsed `only`,
7
+ # `with` and `except` options. A plan reads the selected attributes,
8
+ # the selection of each child plan from `#child`, the preloads of each
9
+ # point from `#preloads`, and its result builder class from
10
+ # `#builder_class`.
11
+ #
12
+ class Selection # :nodoc:
13
+ # Serializer of the selected attributes
14
+ attr_reader :serializer_class
15
+
16
+ # Selects the attributes of the serializer with the parsed selection,
17
+ # Hashes of attribute names
18
+ def initialize(serializer_class, selection)
19
+ @serializer_class = serializer_class
20
+ @only = selection[:only] || FROZEN_EMPTY_HASH
21
+ @with = selection[:with] || FROZEN_EMPTY_HASH
22
+ @except = selection[:except] || FROZEN_EMPTY_HASH
23
+ @only_limits = only_limits?
24
+ end
25
+
26
+ # Returns the selected attributes, in definition order. Reads the
27
+ # attributes on each call: the plan calls it once, after it locks the
28
+ # serializer.
29
+ def attributes
30
+ attributes = []
31
+
32
+ serializer_class.attributes.each_value do |attribute|
33
+ attributes << attribute if visible?(attribute)
34
+ end
35
+
36
+ attributes.freeze
37
+ end
38
+
39
+ # Returns the selection of the child plan of a selected attribute: the
40
+ # relation serializer with the selection of the relation, merged into
41
+ # the presets and the field selection options of the relation. Returns
42
+ # nil for an attribute without a child plan.
43
+ def child(attribute)
44
+ return unless attribute.relation?
45
+
46
+ Selection.new(attribute.serializer, child_selection(attribute))
47
+ end
48
+
49
+ # Returns the result builder class of the plan: SeregaResultBuilder
50
+ def builder_class
51
+ SeregaResultBuilder
52
+ end
53
+
54
+ # Returns the preloads of the point of a selected attribute: the
55
+ # preloads of the attribute
56
+ def preloads(attribute)
57
+ attribute.preloads
58
+ end
59
+
60
+ private
61
+
62
+ # The selection of the relation, merged into the presets and the field
63
+ # selection options of the relation
64
+ def child_selection(attribute)
65
+ name = attribute.name
66
+ selection = {only: @only[name], with: @with[name], except: @except[name]}
67
+ attribute.selection ? Presets.relation_selection(attribute, selection) : selection
68
+ end
69
+
70
+ # `except` without nested fields hides the attribute, `only` and `with`
71
+ # show it, `only` hides the other attributes when it limits this
72
+ # level, and the :hide option decides the rest
73
+ def visible?(attribute)
74
+ name = attribute.name
75
+ return false if @except.member?(name) && @except[name].empty?
76
+ return true if @only.member?(name) || @with.member?(name)
77
+ return false if @only_limits
78
+
79
+ !attribute.hide
80
+ end
81
+
82
+ # `only` hides the fields it does not name when it names a field of
83
+ # this level without nested fields, or when `except` hides no field and
84
+ # `with` adds no field of this level
85
+ def only_limits?
86
+ only = @only
87
+ return false if only.empty?
88
+ return true if only.each_value.any?(&:empty?)
89
+
90
+ @with.empty? && @except.each_value.none?(&:empty?)
91
+ end
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Serega
4
+ class SeregaPlan # :nodoc:
5
+ #
6
+ # Plans of the `only`, `with` and `except` field selection options and
7
+ # of presets. The plans cache calls it to parse, validate and build
8
+ # the plans of its serializer.
9
+ #
10
+ module SelectionPlanner # :nodoc:
11
+ class << self
12
+ # Parses the field selection options as provided: a String, or
13
+ # Symbols, Arrays and Hashes of attribute names. Missing options parse
14
+ # to empty Hashes. The selection of the requested presets is merged in. See
15
+ # Presets.selection.
16
+ def parse(serializer_class, only = nil, with = nil, except = nil, preset = nil)
17
+ selection = {only: parse_option(only), with: parse_option(with), except: parse_option(except)}
18
+ return selection if preset.nil?
19
+
20
+ Presets.selection(serializer_class, preset, selection)
21
+ end
22
+
23
+ # Parses one field selection option as provided: a String, or Symbols,
24
+ # Arrays and Hashes of attribute names. A missing option parses to an
25
+ # empty Hash.
26
+ def parse_option(value)
27
+ return SeregaUtils::ParseStringSelection.parse(value) if value.is_a?(String)
28
+
29
+ SeregaUtils::ToHash.call(value)
30
+ end
31
+
32
+ # Whether the parsed selection names no attributes
33
+ def empty?(selection)
34
+ selection[:only].empty? && selection[:with].empty? && selection[:except].empty?
35
+ end
36
+
37
+ # Raises AttributeNotExist for the attributes the parsed selection
38
+ # name and the serializer does not have
39
+ def validate(serializer_class, selection)
40
+ SeregaValidations::CheckSelection.new.call(serializer_class, selection[:only], selection[:with], selection[:except])
41
+ end
42
+
43
+ # Returns the plan of the serializer with the parsed selection
44
+ def plan(serializer_class, selection)
45
+ SeregaPlan.new(Selection.new(serializer_class, selection))
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end