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



170
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
# File 'lib/super_callbacks.rb', line 170

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



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/super_callbacks.rb', line 134

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