Module: ActiveAdmin::Callbacks::ClassMethods

Defined in:
lib/active_admin/callbacks.rb

Instance Method Summary collapse

Instance Method Details

#define_active_admin_callbacks(*names) ⇒ Object

Define a new callback.

Example:

class MyClassWithCallbacks
  include ActiveAdmin::Callbacks

  define_active_admin_callbacks :save

  before_save do |arg1, arg2|
    # runs before save
  end

  after_save :call_after_save

  def save
    # Will run before, yield, then after
    run_save_callbacks :arg1, :arg2 do
      save!
    end
  end

  protected

  def call_after_save(arg1, arg2)
    # runs after save
  end
end


58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/active_admin/callbacks.rb', line 58

def define_active_admin_callbacks(*names)
 names.each do |name|
   [:before, :after].each do |type|
     # Create an inheritable accessor array for the callbacks
     class_inheritable_array "#{type}_#{name}_callbacks".to_sym
     send("#{type}_#{name}_callbacks=".to_sym, [])

     # Define a method to set the callback
     class_eval("       # def self.before_create\n       def self.\#{type}_\#{name}(method = nil, &block)\n         \#{type}_\#{name}_callbacks << (method || block)\n       end\n     EOS\n   end\n\n   # Define a method to run the callbacks\n   class_eval(<<-EOS, __FILE__, __LINE__ + 1)\n     def run_\#{name}_callbacks(*args)\n       self.class.before_\#{name}_callbacks.each{|callback| call_callback_with(callback, *args)}\n       value = yield if block_given?\n       self.class.after_\#{name}_callbacks.each{|callback| call_callback_with(callback, *args)}\n       return value\n     end\n     EOS\n  end\nend\n", __FILE__, __LINE__ + 1)