Module: AbAdmin::Controllers::Callbacks::ClassMethods

Defined in:
lib/ab_admin/controllers/callbacks.rb

Instance Method Summary collapse

Instance Method Details

#define_admin_callbacks(*names) ⇒ Object

Define a new callback.

Example:

class MyClassWithCallbacks
  include ActiveAdmin::Callbacks

  define_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

93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/ab_admin/controllers/callbacks.rb', line 93

def define_admin_callbacks(*names)
  names.each do |name|
    [:before, :after].each do |type|

      # Define a method to set the callback
      class_eval(<<-EOS, __FILE__, __LINE__ + 1)
      # def self.before_create_callbacks
      def self.#{type}_#{name}_callbacks
        @#{type}_#{name}_callbacks ||= []
      end

      # 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