Class: ViewModel

Inherits:
Object
  • Object
show all
Defined in:
lib/view_model.rb,
lib/view_model/reference.rb,
lib/view_model/references.rb,
lib/view_model/deserialization_error.rb

Direct Known Subclasses

ErrorView::ExceptionDetailView, Record

Defined Under Namespace

Modules: AfterTransactionRunner, Callbacks, Controller, TestHelpers Classes: AbstractError, AbstractErrorCollection, AbstractErrorWithBlame, AccessControl, AccessControlError, ActiveRecord, Changes, Config, DeserializationError, DeserializeContext, Error, ErrorView, Metadata, Record, Reference, References, Registry, Schemas, SerializationError, SerializeContext, TraversalContext, Utils, WrappedExceptionError

Constant Summary collapse

REFERENCE_ATTRIBUTE =
"_ref"
ID_ATTRIBUTE =
"id"
TYPE_ATTRIBUTE =
"_type"
VERSION_ATTRIBUTE =
"_version"
NEW_ATTRIBUTE =
"_new"

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ ViewModel

Returns a new instance of ViewModel.



246
247
248
249
250
# File 'lib/view_model.rb', line 246

def initialize(*args)
  self.class._attributes.each_with_index do |attr, idx|
    self.public_send(:"#{attr}=", args[idx])
  end
end

Class Attribute Details

._attributesObject

Returns the value of attribute _attributes.



20
21
22
# File 'lib/view_model.rb', line 20

def _attributes
  @_attributes
end

.schema_versionObject

Returns the value of attribute schema_version.



21
22
23
# File 'lib/view_model.rb', line 21

def schema_version
  @schema_version
end

.view_aliasesObject (readonly)

Returns the value of attribute view_aliases.



22
23
24
# File 'lib/view_model.rb', line 22

def view_aliases
  @view_aliases
end

.view_nameObject



35
36
37
38
39
40
41
42
43
# File 'lib/view_model.rb', line 35

def view_name
  @view_name ||=
    begin
      # try to auto-detect based on class name
      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

Returns:

  • (Boolean)


233
234
235
# File 'lib/view_model.rb', line 233

def accepts_schema_version?(schema_version)
  schema_version == self.schema_version
end

.add_view_alias(as) ⇒ Object



45
46
47
48
# File 'lib/view_model.rb', line 45

def add_view_alias(as)
  view_aliases << as
  ViewModel::Registry.register(self, as: as)
end

.attribute(attr, **_args) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
# File 'lib/view_model.rb', line 69

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.



65
66
67
# File 'lib/view_model.rb', line 65

def attributes(*attrs, **args)
  attrs.each { |attr| attribute(attr, **args) }
end

.deserialize_context_classObject



225
226
227
# File 'lib/view_model.rb', line 225

def deserialize_context_class
  ViewModel::DeserializeContext
end

.deserialize_from_view(hash_data, references: {}, deserialize_context: new_deserialize_context) ⇒ Object

Rebuild this viewmodel from a serialized hash.



179
180
181
182
183
# File 'lib/view_model.rb', line 179

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



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/view_model.rb', line 185

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|
      if view_hash.has_key?(attr)
        viewmodel.public_send("deserialize_#{attr}",
                              view_hash[attr],
                              references: references,
                              deserialize_context: deserialize_context)
      end
    end

    deserialize_context.run_callback(ViewModel::Callbacks::Hook::BeforeValidate, viewmodel)
    viewmodel.validate!

    # More complex viewmodels can use this hook to track changes to
    # persistent backing models, and record the results. Primitive
    # viewmodels record no changes.
    if block_given?
      yield(hook_control)
    else
      hook_control.record_changes(Changes.new)
    end
  end
end

.eager_includes(serialize_context: new_serialize_context, include_referenced: true) ⇒ Object

If this viewmodel represents an AR model, what associations does it make use of? Returns a includes spec appropriate for DeepPreloader, either as AR-style nested hashes or DeepPreloader::Spec.



128
129
130
# File 'lib/view_model.rb', line 128

def eager_includes(serialize_context: new_serialize_context, include_referenced: true)
  {}
end

.encode_json(value) ⇒ Object



167
168
169
170
171
172
173
174
175
176
# File 'lib/view_model.rb', line 167

def encode_json(value)
  # Jbuilder#encode no longer uses MultiJson, but instead calls `.to_json`. In
  # the context of ActiveSupport, we don't want this, because AS replaces the
  # .to_json interface with its own .as_json, which demands that everything is
  # reduced to a Hash before it can be JSON encoded. Using this is not only
  # slightly more expensive in terms of allocations, but also defeats the
  # purpose of our precompiled `CompiledJson` terminals. Instead serialize
  # using OJ with options equivalent to those used by MultiJson.
  Oj.dump(value, mode: :compat, time_format: :ruby, use_to_json: true)
end

.extract_reference_metadata(hash) ⇒ Object



114
115
116
117
# File 'lib/view_model.rb', line 114

def (hash)
  ViewModel::Schemas.verify_schema!(ViewModel::Schemas::VIEWMODEL_REFERENCE, hash)
  hash.delete(ViewModel::REFERENCE_ATTRIBUTE)
end

.extract_reference_only_metadata(hash) ⇒ Object



106
107
108
109
110
111
112
# File 'lib/view_model.rb', line 106

def (hash)
  ViewModel::Schemas.verify_schema!(ViewModel::Schemas::VIEWMODEL_UPDATE, hash)
  id             = hash.delete(ViewModel::ID_ATTRIBUTE)
  type_name      = hash.delete(ViewModel::TYPE_ATTRIBUTE)

  .new(id, type_name, nil, false)
end

.extract_viewmodel_metadata(hash) ⇒ Object

In deserialization, verify and extract metadata from a provided hash.



96
97
98
99
100
101
102
103
104
# File 'lib/view_model.rb', line 96

def (hash)
  ViewModel::Schemas.verify_schema!(ViewModel::Schemas::VIEWMODEL_UPDATE, hash)
  id             = hash.delete(ViewModel::ID_ATTRIBUTE)
  type_name      = hash.delete(ViewModel::TYPE_ATTRIBUTE)
  schema_version = hash.delete(ViewModel::VERSION_ATTRIBUTE)
  new            = hash.delete(ViewModel::NEW_ATTRIBUTE) { false }

  .new(id, type_name, schema_version, new)
end

.inherited(subclass) ⇒ Object



25
26
27
# File 'lib/view_model.rb', line 25

def inherited(subclass)
  subclass.initialize_as_viewmodel
end

.initialize_as_viewmodelObject



29
30
31
32
33
# File 'lib/view_model.rb', line 29

def initialize_as_viewmodel
  @_attributes    = []
  @schema_version = 1
  @view_aliases   = []
end

.is_update_hash?(hash) ⇒ Boolean

Returns:

  • (Boolean)


119
120
121
122
123
# File 'lib/view_model.rb', line 119

def is_update_hash?(hash)
  ViewModel::Schemas.verify_schema!(ViewModel::Schemas::VIEWMODEL_UPDATE, hash)
  hash.has_key?(ViewModel::ID_ATTRIBUTE) &&
    !hash.fetch(ViewModel::ActiveRecord::NEW_ATTRIBUTE, false)
end

.lock_attribute_inheritanceObject

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.



84
85
86
87
88
89
# File 'lib/view_model.rb', line 84

def lock_attribute_inheritance
  _attributes.tap do |attrs|
    define_singleton_method(:_attributes) { attrs }
    attrs.freeze
  end
end

.member_namesObject



91
92
93
# File 'lib/view_model.rb', line 91

def member_names
  _attributes
end

.new_deserialize_context(*args) ⇒ Object



229
230
231
# File 'lib/view_model.rb', line 229

def new_deserialize_context(*args)
  deserialize_context_class.new(*args)
end

.new_serialize_context(*args) ⇒ Object



221
222
223
# File 'lib/view_model.rb', line 221

def new_serialize_context(*args)
  serialize_context_class.new(*args)
end

.preload_for_serialization(viewmodels, serialize_context: new_serialize_context, include_referenced: true, lock: nil) ⇒ Object



237
238
239
240
241
242
243
# File 'lib/view_model.rb', line 237

def preload_for_serialization(viewmodels, serialize_context: new_serialize_context, include_referenced: true, lock: nil)
  Array.wrap(viewmodels).group_by(&:class).each do |type, views|
    DeepPreloader.preload(views.map(&:model),
                          type.eager_includes(serialize_context: serialize_context, include_referenced: include_referenced),
                          lock: lock)
  end
end

.root!Object



58
59
60
# File 'lib/view_model.rb', line 58

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.

Returns:

  • (Boolean)


54
55
56
# File 'lib/view_model.rb', line 54

def root?
  false
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).



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/view_model.rb', line 134

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



154
155
156
157
158
159
160
161
# File 'lib/view_model.rb', line 154

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_classObject



217
218
219
# File 'lib/view_model.rb', line 217

def serialize_context_class
  ViewModel::SerializeContext
end

.serialize_to_hash(viewmodel, serialize_context: new_serialize_context) ⇒ Object



163
164
165
# File 'lib/view_model.rb', line 163

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?



328
329
330
331
332
# File 'lib/view_model.rb', line 328

def ==(other)
  other.class == self.class && self.class._attributes.all? do |attr|
    other.send(attr) == self.send(attr)
  end
end

#blame_referenceObject

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.



316
317
318
# File 'lib/view_model.rb', line 316

def blame_reference
  to_reference
end

#context_for_child(member_name, context:) ⇒ Object



320
321
322
# File 'lib/view_model.rb', line 320

def context_for_child(member_name, context:)
  context.for_child(self, association_name: member_name)
end

#hashObject



336
337
338
339
340
# File 'lib/view_model.rb', line 336

def hash
  features = self.class._attributes.map { |attr| self.send(attr) }
  features << self.class
  features.hash
end

#idObject

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.



290
291
292
# File 'lib/view_model.rb', line 290

def id
  object_id
end

#modelObject

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.



281
282
283
# File 'lib/view_model.rb', line 281

def model
  self.public_send(self.class._attributes.first)
end

#preload_for_serialization(lock: nil, serialize_context: self.class.new_serialize_context) ⇒ Object



324
325
326
# File 'lib/view_model.rb', line 324

def preload_for_serialization(lock: nil, serialize_context: self.class.new_serialize_context)
  ViewModel.preload_for_serialization([self], lock: lock, serialize_context: serialize_context)
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.



254
255
256
257
258
# File 'lib/view_model.rb', line 254

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_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.



270
271
272
273
274
275
276
# File 'lib/view_model.rb', line 270

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.

Returns:

  • (Boolean)


297
298
299
# File 'lib/view_model.rb', line 297

def stable_id?
  false
end

#to_hash(serialize_context: self.class.new_serialize_context) ⇒ Object



260
261
262
# File 'lib/view_model.rb', line 260

def to_hash(serialize_context: self.class.new_serialize_context)
  Jbuilder.new { |json| serialize(json, serialize_context: serialize_context) }.attributes!
end

#to_json(serialize_context: self.class.new_serialize_context) ⇒ Object



264
265
266
# File 'lib/view_model.rb', line 264

def to_json(serialize_context: self.class.new_serialize_context)
  ViewModel.encode_json(self.to_hash(serialize_context: serialize_context))
end

#to_referenceObject



303
304
305
# File 'lib/view_model.rb', line 303

def to_reference
  ViewModel::Reference.new(self.class, (id if stable_id?))
end

#validate!Object



301
# File 'lib/view_model.rb', line 301

def validate!; end

#view_nameObject

Delegate view_name to class in most cases. Polymorphic views may wish to override this to select a specific alias.



309
310
311
# File 'lib/view_model.rb', line 309

def view_name
  self.class.view_name
end