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(<<-EOS, __FILE__, __LINE__ + 1)
       # def self.before_create
       def self.#{type}_#{name}(method = nil, &block)
         #{type}_#{name}_callbacks << (method || block)
       end
     EOS
   end

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