Module: SuperCallbacks::InstanceMethods

Defined in:
lib/super_callbacks/instance_methods.rb

Overview

The methods defined here will be available “class” methods for any class where SuperCallbacks is included

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



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/super_callbacks/instance_methods.rb', line 42

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



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/super_callbacks/instance_methods.rb', line 6

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