Module: ViewModel::Callbacks

Extended by:
ActiveSupport::Concern
Included in:
AccessControl
Defined in:
lib/view_model/callbacks.rb

Overview

Callback hooks for viewmodel traversal contexts

Defined Under Namespace

Modules: CallbackEnvContext Classes: DeserializeHookControl

Constant Summary collapse

ALWAYS =

Placeholder for callbacks to invoked for all view types

'__always'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.wrap_deserialize(viewmodel, deserialize_context:) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/view_model/callbacks.rb', line 200

def self.wrap_deserialize(viewmodel, deserialize_context:)
  hook_control = DeserializeHookControl.new

  wrap_serialize(viewmodel, context: deserialize_context) do
    deserialize_context.run_callback(ViewModel::Callbacks::Hook::BeforeDeserialize,
                                     viewmodel)

    val = yield(hook_control)

    if hook_control.changes.nil?
      raise ViewModel::DeserializationError::Internal.new(
              'Internal error: changes not recorded for deserialization of viewmodel',
              viewmodel.blame_reference)
    end

    deserialize_context.run_callback(ViewModel::Callbacks::Hook::AfterDeserialize,
                                     viewmodel,
                                     changes: hook_control.changes)
    val
  end
end

.wrap_serialize(viewmodel, context:) ⇒ Object



187
188
189
190
191
192
# File 'lib/view_model/callbacks.rb', line 187

def self.wrap_serialize(viewmodel, context:)
  context.run_callback(ViewModel::Callbacks::Hook::BeforeVisit, viewmodel)
  val = yield
  context.run_callback(ViewModel::Callbacks::Hook::AfterVisit, viewmodel)
  val
end

Instance Method Details

#ineligible(view) ⇒ Object



180
181
182
183
184
185
# File 'lib/view_model/callbacks.rb', line 180

def ineligible(view)
  # ARVM synthetic views are considered part of their association and as such
  # are not visited by callbacks. Eligibility exclusion is intended to be
  # library-internal: subclasses should not attempt to extend this.
  view.is_a?(ViewModel::ActiveRecord) && view.class.synthetic
end

#run_callback(hook, view, context, **args) ⇒ Object



169
170
171
172
173
174
175
176
177
178
# File 'lib/view_model/callbacks.rb', line 169

def run_callback(hook, view, context, **args)
  return if ineligible(view)

  callback_env = hook.env_class.create(self, view, context, **args)

  view_name = view.class.view_name
  self.class.each_callback(hook, view_name) do |callback|
    callback_env.instance_exec(&callback)
  end
end