Module: ActiveRecord::Reactor::Callbacks::ClassMethods

Defined in:
lib/active_record/reactor/callbacks.rb

Instance Method Summary collapse

Instance Method Details

#define_reactor_callbacks(*args) ⇒ Object

Define a custom model callback, which is available to reactors registered with that model. Works like ActiveModel::define_model_callbacks, but does not define around callbacks by default.

Make sure to define any custom callbacks before registering any reactors with your model that should react on that callback.



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/active_record/reactor/callbacks.rb', line 22

def define_reactor_callbacks(*args)
  options = args.extract_options!
  options[:only] ||= [:before, :after] # TODO: implement around callbacks
  types = Array.wrap(options[:only])
  define_model_callbacks(*(args.dup << options))
  def args.combine(other, &block)
    return product(other) unless block_given?
    product(other).inject([]) { |result, ab| result << yield(ab.first, ab.last) }
  end
  self.reactor_callbacks = (reactor_callbacks + args.combine(types) { |arg, type| :"#{type}_#{arg}" }).uniq
end

#reactor(klass_or_name) ⇒ Object

Register a reactor with the model. Note that only callbacks defined on the reactor at the time of registration will be called.

<tt>klass_or_name<tt> can be an actual reactor class, or a string or symbol.

class Banana < ActiveRecord::Base
  # register YummyReactor
  reactor :yummy

  # register reactor CustomName
  reactor CustomName
end


47
48
49
50
51
52
# File 'lib/active_record/reactor/callbacks.rb', line 47

def reactor(klass_or_name)
  reactor = klass_or_name.is_a?(Class) ? klass_or_name : "#{klass_or_name.to_s.camelize}Reactor".constantize
  (reactor.callbacks & self.reactor_callbacks).each do |callback|
    send(callback) { |record| reactor.instance.send(callback, record) unless reactor.scrammed?; true }
  end
end