Class: ViewModel
- Inherits:
-
Object
show all
- Defined in:
- lib/view_model.rb,
lib/view_model/migrator.rb,
lib/view_model/reference.rb,
lib/view_model/references.rb,
lib/view_model/error_wrapping.rb,
lib/view_model/deserialization_error.rb
Defined Under Namespace
Modules: AfterTransactionRunner, Callbacks, Controller, ErrorWrapping, MigratableView, TestHelpers
Classes: AbstractError, AbstractErrorCollection, AbstractErrorWithBlame, AccessControl, AccessControlError, ActiveRecord, Changes, Config, DeserializationError, DeserializeContext, DownMigrator, Error, ErrorView, GarbageCollection, Metadata, Migration, Migrator, Record, Reference, References, Registry, Schemas, SerializationError, SerializeContext, TraversalContext, UpMigrator, Utils, WrappedExceptionError
Constant Summary
collapse
- REFERENCE_ATTRIBUTE =
'_ref'
- ID_ATTRIBUTE =
'id'
- TYPE_ATTRIBUTE =
'_type'
- VERSION_ATTRIBUTE =
'_version'
- NEW_ATTRIBUTE =
The optional _new attribute specifies explicitly whether a deserialization is to an new or existing model. The behaviour of _new is as follows:
* true - Always create a new model, using the id if provided, error if
a model with that id already exists
* false - Never create a new model. If id isn’t provided, it's an error
unless the viewmodel is being deserialized in the context of a
singular association, in which case it's implicitly referring
to the current child of that association, and is an error if
that child doesn't exist.
-
nil - Create a new model if id is not specified, otherwise update the
existing record with `id`, and error if it doesn't exist.
-
‘auto’ - Can only be used when the viewmodel is being deserialized in the
context of a singular association. `id` must not be specified. If
the association currently has a child, update it, otherwise
create a new one.
'_new'
- BULK_UPDATE_TYPE =
'_bulk_update'
- BULK_UPDATES_ATTRIBUTE =
'updates'
- BULK_UPDATE_ATTRIBUTE =
'update'
- MIGRATED_ATTRIBUTE =
Migrations leave a metadata attribute _migrated on any views that they alter. This attribute is accessible as metadata when deserializing migrated input, and is included in the output serialization sent to clients.
'_migrated'
Class Attribute Summary collapse
Class Method Summary
collapse
-
.accepts_schema_version?(schema_version) ⇒ Boolean
-
.add_view_alias(as) ⇒ Object
-
.attribute(attr, **_args) ⇒ Object
-
.attributes(*attrs, **args) ⇒ Object
ViewModels are typically going to be pretty simple structures.
-
.deserialization_includes ⇒ Object
If this viewmodel represents an AR model, what associations does it make use of during deserialization? By default all mentioned associations are preloaded, however access controls and hooks may benefit from additional preloading.
-
.deserialize_context_class ⇒ Object
-
.deserialize_from_view(hash_data, references: {}, deserialize_context: new_deserialize_context) ⇒ Object
Rebuild this viewmodel from a serialized hash.
-
.deserialize_members_from_view(viewmodel, view_hash, references:, deserialize_context:) ⇒ Object
-
.eager_includes(include_referenced: true) ⇒ Object
If this viewmodel represents an AR model, what associations does it make use of during serialization? Returns a includes spec appropriate for DeepPreloader, either as AR-style nested hashes or DeepPreloader::Spec.
-
.encode_json(value) ⇒ Object
-
.extract_reference_metadata(hash) ⇒ Object
-
.extract_reference_only_metadata(hash) ⇒ Object
-
.extract_viewmodel_metadata(hash) ⇒ Object
In deserialization, verify and extract metadata from a provided hash.
-
.inherited(subclass) ⇒ Object
-
.initialize_as_viewmodel ⇒ Object
-
.is_update_hash?(hash) ⇒ Boolean
rubocop:disable Naming/PredicateName.
-
.lock_attribute_inheritance ⇒ Object
An abstract viewmodel may want to define attributes to be shared by their subclasses.
-
.member_names ⇒ Object
-
.new_deserialize_context ⇒ Object
-
.new_serialize_context ⇒ Object
-
.preload_for_serialization(viewmodels, include_referenced: true, lock: nil) ⇒ Object
-
.root! ⇒ Object
-
.root? ⇒ Boolean
ViewModels are either roots or children.
-
.schema_hash(schema_versions) ⇒ Object
-
.schema_versions(viewmodels) ⇒ Object
-
.serialize(target, json, serialize_context: new_serialize_context) ⇒ Object
ViewModel can serialize ViewModels, Arrays and Hashes of ViewModels, and relies on Jbuilder#merge! for other values (e.g. primitives).
-
.serialize_as_reference(target, json, serialize_context: new_serialize_context) ⇒ Object
-
.serialize_context_class ⇒ Object
-
.serialize_from_cache(views, migration_versions: {}, locked: false, serialize_context:) ⇒ Object
-
.serialize_to_hash(viewmodel, serialize_context: new_serialize_context) ⇒ Object
Instance Method Summary
collapse
Constructor Details
#initialize(*args) ⇒ ViewModel
Returns a new instance of ViewModel.
351
352
353
354
355
|
# File 'lib/view_model.rb', line 351
def initialize(*args)
self.class._attributes.each_with_index do |attr, idx|
self.public_send(:"#{attr}=", args[idx])
end
end
|
Class Attribute Details
._attributes ⇒ Object
Returns the value of attribute _attributes.
72
73
74
|
# File 'lib/view_model.rb', line 72
def _attributes
@_attributes
end
|
.schema_version ⇒ Object
Returns the value of attribute schema_version.
73
74
75
|
# File 'lib/view_model.rb', line 73
def schema_version
@schema_version
end
|
.synthetic ⇒ Object
Boolean to indicate if the viewmodel is synthetic. Synthetic viewmodels are nearly-invisible glue. They’re full viewmodels, but do not participate in hooks or registration. For example, a join table connecting A and B through T has a synthetic viewmodel T to represent the join model, but the external interface is a relationship of A to a list of Bs.
83
84
85
|
# File 'lib/view_model.rb', line 83
def synthetic
@synthetic
end
|
.view_aliases ⇒ Object
Returns the value of attribute view_aliases.
74
75
76
|
# File 'lib/view_model.rb', line 74
def view_aliases
@view_aliases
end
|
.view_name ⇒ Object
96
97
98
99
100
101
102
103
104
105
|
# File 'lib/view_model.rb', line 96
def view_name
@view_name ||=
begin
match = /(.*)View$/.match(self.name)
raise ArgumentError.new("Could not auto-determine ViewModel name from class name '#{self.name}'") if match.nil?
ViewModel::Registry.default_view_name(match[1])
end
end
|
Class Method Details
.accepts_schema_version?(schema_version) ⇒ Boolean
322
323
324
|
# File 'lib/view_model.rb', line 322
def accepts_schema_version?(schema_version)
schema_version == self.schema_version
end
|
.add_view_alias(as) ⇒ Object
107
108
109
110
|
# File 'lib/view_model.rb', line 107
def add_view_alias(as)
view_aliases << as
ViewModel::Registry.register(self, as: as)
end
|
.attribute(attr, **_args) ⇒ Object
131
132
133
134
135
136
137
138
139
140
141
142
|
# File 'lib/view_model.rb', line 131
def attribute(attr, **_args)
unless attr.is_a?(Symbol)
raise ArgumentError.new('ViewModel attributes must be symbols')
end
attr_accessor attr
define_method("deserialize_#{attr}") do |value, references: {}, deserialize_context: self.class.new_deserialize_context|
self.public_send("#{attr}=", value)
end
_attributes << attr
end
|
.attributes(*attrs, **args) ⇒ Object
ViewModels are typically going to be pretty simple structures. Make it a bit easier to define them: attributes specified this way are given accessors and assigned in order by the default constructor.
127
128
129
|
# File 'lib/view_model.rb', line 127
def attributes(*attrs, **args)
attrs.each { |attr| attribute(attr, **args) }
end
|
.deserialization_includes ⇒ Object
If this viewmodel represents an AR model, what associations does it make use of during deserialization? By default all mentioned associations are preloaded, however access controls and hooks may benefit from additional preloading. Returns a includes spec appropriate for DeepPreloader, either as AR-style nested hashes or DeepPreloader::Spec.
206
207
208
|
# File 'lib/view_model.rb', line 206
def deserialization_includes
{}
end
|
.deserialize_context_class ⇒ Object
.deserialize_from_view(hash_data, references: {}, deserialize_context: new_deserialize_context) ⇒ Object
Rebuild this viewmodel from a serialized hash.
268
269
270
271
272
|
# File 'lib/view_model.rb', line 268
def deserialize_from_view(hash_data, references: {}, deserialize_context: new_deserialize_context)
viewmodel = self.new
deserialize_members_from_view(viewmodel, hash_data, references: references, deserialize_context: deserialize_context)
viewmodel
end
|
.deserialize_members_from_view(viewmodel, view_hash, references:, deserialize_context:) ⇒ Object
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
|
# File 'lib/view_model.rb', line 274
def deserialize_members_from_view(viewmodel, view_hash, references:, deserialize_context:)
ViewModel::Callbacks.wrap_deserialize(viewmodel, deserialize_context: deserialize_context) do |hook_control|
if (bad_attrs = view_hash.keys - member_names).present?
causes = bad_attrs.map do |bad_attr|
ViewModel::DeserializationError::UnknownAttribute.new(bad_attr, viewmodel.blame_reference)
end
raise ViewModel::DeserializationError::Collection.for_errors(causes)
end
member_names.each do |attr|
next unless view_hash.has_key?(attr)
viewmodel.public_send("deserialize_#{attr}",
view_hash[attr],
references: references,
deserialize_context: deserialize_context)
end
deserialize_context.run_callback(ViewModel::Callbacks::Hook::BeforeValidate, viewmodel)
viewmodel.validate!
if block_given?
yield(hook_control)
else
hook_control.record_changes(Changes.new)
end
end
end
|
.eager_includes(include_referenced: true) ⇒ Object
If this viewmodel represents an AR model, what associations does it make use of during serialization? Returns a includes spec appropriate for DeepPreloader, either as AR-style nested hashes or DeepPreloader::Spec.
197
198
199
|
# File 'lib/view_model.rb', line 197
def eager_includes(include_referenced: true)
{}
end
|
.encode_json(value) ⇒ Object
256
257
258
259
260
261
262
263
264
265
|
# File 'lib/view_model.rb', line 256
def encode_json(value)
Oj.dump(value, mode: :compat, time_format: :ruby, use_to_json: true)
end
|
In deserialization, verify and extract metadata from a provided hash.
.inherited(subclass) ⇒ Object
85
86
87
88
|
# File 'lib/view_model.rb', line 85
def inherited(subclass)
super
subclass.initialize_as_viewmodel
end
|
.initialize_as_viewmodel ⇒ Object
90
91
92
93
94
|
# File 'lib/view_model.rb', line 90
def initialize_as_viewmodel
@_attributes = []
@schema_version = 1
@view_aliases = []
end
|
.is_update_hash?(hash) ⇒ Boolean
rubocop:disable Naming/PredicateName
.lock_attribute_inheritance ⇒ Object
An abstract viewmodel may want to define attributes to be shared by their subclasses. Redefine _attributes to close over the current class’s _attributes and ignore children.
147
148
149
150
151
152
|
# File 'lib/view_model.rb', line 147
def lock_attribute_inheritance
_attributes.tap do |attrs|
define_singleton_method(:_attributes) { attrs }
attrs.freeze
end
end
|
.member_names ⇒ Object
154
155
156
|
# File 'lib/view_model.rb', line 154
def member_names
_attributes.map(&:to_s)
end
|
.new_deserialize_context ⇒ Object
318
319
320
|
# File 'lib/view_model.rb', line 318
def new_deserialize_context(...)
deserialize_context_class.new(...)
end
|
.new_serialize_context ⇒ Object
310
311
312
|
# File 'lib/view_model.rb', line 310
def new_serialize_context(...)
serialize_context_class.new(...)
end
|
.preload_for_serialization(viewmodels, include_referenced: true, lock: nil) ⇒ Object
339
340
341
342
343
344
345
346
347
348
|
# File 'lib/view_model.rb', line 339
def preload_for_serialization(viewmodels, include_referenced: true, lock: nil)
Array.wrap(viewmodels)
.flat_map { |v| v.preloadable_dependencies(include_referenced: include_referenced) }
.group_by(&:class)
.each do |type, views|
DeepPreloader.preload(views.map(&:model),
type.eager_includes(include_referenced: include_referenced),
lock: lock)
end
end
|
.root! ⇒ Object
120
121
122
|
# File 'lib/view_model.rb', line 120
def root!
define_singleton_method(:root?) { true }
end
|
.root? ⇒ Boolean
ViewModels are either roots or children. Root viewmodels may be (de)serialized directly, whereas child viewmodels are always nested within their parent. Associations to root viewmodel types always use indirect references.
116
117
118
|
# File 'lib/view_model.rb', line 116
def root?
false
end
|
.schema_hash(schema_versions) ⇒ Object
332
333
334
335
336
337
|
# File 'lib/view_model.rb', line 332
def schema_hash(schema_versions)
version_string = schema_versions.to_a.sort.join(',')
hash = Digest::SHA256.digest(version_string).byteslice(0, 16)
Base64.urlsafe_encode64(hash, padding: false)
end
|
.schema_versions(viewmodels) ⇒ Object
326
327
328
329
330
|
# File 'lib/view_model.rb', line 326
def schema_versions(viewmodels)
viewmodels.each_with_object({}) do |view, h|
h[view.view_name] = view.schema_version
end
end
|
.serialize(target, json, serialize_context: new_serialize_context) ⇒ Object
ViewModel can serialize ViewModels, Arrays and Hashes of ViewModels, and relies on Jbuilder#merge! for other values (e.g. primitives).
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
|
# File 'lib/view_model.rb', line 212
def serialize(target, json, serialize_context: new_serialize_context)
case target
when ViewModel
target.serialize(json, serialize_context: serialize_context)
when Array
json.array! target do |elt|
serialize(elt, json, serialize_context: serialize_context)
end
when Hash, Struct
json.merge!({})
target.each_pair do |key, value|
json.set! key do
serialize(value, json, serialize_context: serialize_context)
end
end
else
json.merge! target
end
end
|
.serialize_as_reference(target, json, serialize_context: new_serialize_context) ⇒ Object
232
233
234
235
236
237
238
239
|
# File 'lib/view_model.rb', line 232
def serialize_as_reference(target, json, serialize_context: new_serialize_context)
if serialize_context.flatten_references
serialize(target, json, serialize_context: serialize_context)
else
ref = serialize_context.add_reference(target)
json.set!(REFERENCE_ATTRIBUTE, ref)
end
end
|
.serialize_context_class ⇒ Object
.serialize_from_cache(views, migration_versions: {}, locked: false, serialize_context:) ⇒ Object
245
246
247
248
249
250
251
252
253
254
|
# File 'lib/view_model.rb', line 245
def serialize_from_cache(views, migration_versions: {}, locked: false, serialize_context:)
plural = views.is_a?(Array)
views = Array.wrap(views)
json_views, json_refs = ViewModel::ActiveRecord::Cache.render_viewmodels_from_cache(
views, locked: locked, migration_versions: migration_versions, serialize_context: serialize_context)
json_views = json_views.first unless plural
return json_views, json_refs
end
|
.serialize_to_hash(viewmodel, serialize_context: new_serialize_context) ⇒ Object
241
242
243
|
# File 'lib/view_model.rb', line 241
def serialize_to_hash(viewmodel, serialize_context: new_serialize_context)
Jbuilder.new { |json| serialize(viewmodel, json, serialize_context: serialize_context) }.attributes!
end
|
Instance Method Details
#==(other) ⇒ Object
Also known as:
eql?
441
442
443
444
445
|
# File 'lib/view_model.rb', line 441
def ==(other)
other.class == self.class && self.class._attributes.all? do |attr|
other.send(attr) == self.send(attr)
end
end
|
#blame_reference ⇒ Object
When deserializing, if an error occurs within this viewmodel, what viewmodel is reported as to blame. Can be overridden for example when a viewmodel is merged with its parent.
421
422
423
|
# File 'lib/view_model.rb', line 421
def blame_reference
to_reference
end
|
#context_for_child(member_name, context:) ⇒ Object
425
426
427
|
# File 'lib/view_model.rb', line 425
def context_for_child(member_name, context:)
context.for_child(self, association_name: member_name)
end
|
#hash ⇒ Object
449
450
451
452
453
|
# File 'lib/view_model.rb', line 449
def hash
features = self.class._attributes.map { |attr| self.send(attr) }
features << self.class
features.hash
end
|
#id ⇒ Object
Provide a stable way to identify this view through attribute changes. By default views cannot make assumptions about the identity of our attributes, so we fall back on the view’s object_id. If a viewmodel is backed by a model with a concept of identity, this method should be overridden to use it.
395
396
397
|
# File 'lib/view_model.rb', line 395
def id
object_id
end
|
#model ⇒ Object
ViewModels are often used to serialize ActiveRecord models. For convenience, if necessary we assume that the wrapped model is the first attribute. To change this, override this method.
386
387
388
|
# File 'lib/view_model.rb', line 386
def model
self.public_send(self.class._attributes.first)
end
|
#preload_for_serialization(include_referenced: true, lock: nil) ⇒ Object
429
430
431
|
# File 'lib/view_model.rb', line 429
def preload_for_serialization(include_referenced: true, lock: nil)
ViewModel.preload_for_serialization([self], include_referenced: include_referenced, lock: lock)
end
|
#preloadable_dependencies(include_referenced: true) ⇒ Object
Returns a collection of zero or more AR-backed views that this view depends on that can have their dependencies preloaded via eager_includes. This can be overridden for non-AR view that wrap AR-backed views to expose those dependencies for preloading.
437
438
439
|
# File 'lib/view_model.rb', line 437
def preloadable_dependencies(include_referenced: true)
[]
end
|
#serialize(json, serialize_context: self.class.new_serialize_context) ⇒ Object
Serialize this viewmodel to a jBuilder by calling serialize_view. May be overridden in subclasses to (for example) implement caching.
359
360
361
362
363
|
# File 'lib/view_model.rb', line 359
def serialize(json, serialize_context: self.class.new_serialize_context)
ViewModel::Callbacks.wrap_serialize(self, context: serialize_context) do
serialize_view(json, serialize_context: serialize_context)
end
end
|
#serialize_to_hash(serialize_context: self.class.new_serialize_context) ⇒ Object
365
366
367
|
# File 'lib/view_model.rb', line 365
def serialize_to_hash(serialize_context: self.class.new_serialize_context)
Jbuilder.new { |json| serialize(json, serialize_context: serialize_context) }.attributes!
end
|
#serialize_view(json, serialize_context: self.class.new_serialize_context) ⇒ Object
Render this viewmodel to a jBuilder. Usually overridden in subclasses. Default implementation visits each attribute with Viewmodel.serialize.
375
376
377
378
379
380
381
|
# File 'lib/view_model.rb', line 375
def serialize_view(json, serialize_context: self.class.new_serialize_context)
self.class._attributes.each do |attr|
json.set! attr do
ViewModel.serialize(self.send(attr), json, serialize_context: serialize_context)
end
end
end
|
#stable_id? ⇒ Boolean
Is this viewmodel backed by a model with a stable identity? Used to decide whether the id is included when constructing a ViewModel::Reference from this view.
402
403
404
|
# File 'lib/view_model.rb', line 402
def stable_id?
false
end
|
#to_json(serialize_context: self.class.new_serialize_context) ⇒ Object
369
370
371
|
# File 'lib/view_model.rb', line 369
def to_json(serialize_context: self.class.new_serialize_context)
ViewModel.encode_json(self.serialize_to_hash(serialize_context: serialize_context))
end
|
#to_reference ⇒ Object
408
409
410
|
# File 'lib/view_model.rb', line 408
def to_reference
ViewModel::Reference.new(self.class, (id if stable_id?))
end
|
#validate! ⇒ Object
406
|
# File 'lib/view_model.rb', line 406
def validate!; end
|
#view_name ⇒ Object
Delegate view_name to class in most cases. Polymorphic views may wish to override this to select a specific alias.
414
415
416
|
# File 'lib/view_model.rb', line 414
def view_name
self.class.view_name
end
|