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