Module: SuperCallbacks::InstanceMethods

Defined in:
lib/super_callbacks.rb

Instance Method Summary collapse

Instance Method Details

#run_after_callbacks(method_name, *args) ⇒ Object

TODO: optimize by instead of dynamically getting all_ancestral_after_callbacks on runtime set them immediately when ‘include` is called on Base class



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/super_callbacks.rb', line 207

def run_after_callbacks(method_name, *args)
  all_ancestral_after_callbacks = self.class.ancestors.reverse.each_with_object({}) do |ancestor, hash|
    SuperCallbacks::Helpers.deep_merge_hashes_and_combine_arrays!(
      hash,
      ancestor.instance_variable_get(:@after_callbacks) || {}
    )
  end

  singleton_class_after_callbacks = instance_variable_get(:@after_callbacks) || {}

  all_after_callbacks = SuperCallbacks::Helpers.deep_merge_hashes_and_combine_arrays(
    all_ancestral_after_callbacks,
    singleton_class_after_callbacks
  )

  all_after_callbacks_on_method = all_after_callbacks[method_name] || []

  all_after_callbacks_on_method.each do |after_callback, options_if|
    is_condition_truthy = true

    if options_if
      is_condition_truthy = instance_exec *args, &options_if
    end

    if is_condition_truthy
      if after_callback.is_a? Proc
        instance_exec *args, &after_callback
      else
        send after_callback
      end
    end
  end
end

#run_before_callbacks(method_name, *args) ⇒ Object

TODO: optimize by instead of dynamically getting all_ancestral_after_callbacks on runtime set them immediately when ‘include` is called on Base class



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/super_callbacks.rb', line 171

def run_before_callbacks(method_name, *args)
  all_ancestral_before_callbacks = self.class.ancestors.reverse.each_with_object({}) do |ancestor, hash|
    SuperCallbacks::Helpers.deep_merge_hashes_and_combine_arrays!(
      hash,
      ancestor.instance_variable_get(:@before_callbacks) || {}
    )
  end

  singleton_class_before_callbacks = instance_variable_get(:@before_callbacks) || {}

  all_before_callbacks = SuperCallbacks::Helpers.deep_merge_hashes_and_combine_arrays(
    all_ancestral_before_callbacks,
    singleton_class_before_callbacks
  )

  all_before_callbacks_on_method = all_before_callbacks[method_name] || []

  all_before_callbacks_on_method.each do |before_callback, options_if|
    is_condition_truthy = true

    if options_if
      is_condition_truthy = instance_exec *args, &options_if
    end

    if is_condition_truthy
      if before_callback.is_a? Proc
        instance_exec *args, &before_callback
      else
        send before_callback
      end
    end
  end
end