Module: EmbedCallbacks::PrependMethods

Defined in:
lib/embed_callbacks.rb

Instance Method Summary collapse

Instance Method Details

#set_callback(target_method_name, behavior_sym, callback_function_name, **options) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/embed_callbacks.rb', line 9

def set_callback(target_method_name, behavior_sym, callback_function_name, **options)
  behavior = Behavior.new(behavior_sym)
  m = Module.new
  m.define_method(target_method_name) do |*params|
    condition = Condition.new(options).call(self)
    begin
      method(callback_function_name).call if condition && behavior.before?
      return_value = super(*params)
      method(callback_function_name).call if condition && behavior.after?
      return_value
    rescue => e
      method(callback_function_name).call if condition && behavior.rescue?
      raise e
    ensure
      method(callback_function_name).call if condition && behavior.ensure?
    end
  end
  prepend m
end