module Ardm::Ar::Hooks::ClassMethods

Public Instance Methods

_ardm_hook(order, event, meth=nil, &block) click to toggle source
# File lib/ardm/ar/hooks.rb, line 38
def _ardm_hook(order, event, meth=nil, &block)
  if event.to_sym == :valid?
    event = "validation"
  end

  callback_name = "#{order}_#{event}".to_sym
  if !ActiveRecord::Callbacks::CALLBACKS.include?(callback_name)
    _define_callbacks_and_wrap_original_method(event.to_sym)
  end

  if meth.nil?
    send callback_name, &block
  else
    send callback_name, meth
  end
end
_callbacks_method(name) click to toggle source
# File lib/ardm/ar/hooks.rb, line 64
def _callbacks_method(name)
  "_with_callbacks_#{name}".to_sym
end
_define_callbacks_and_wrap_original_method(name) click to toggle source
# File lib/ardm/ar/hooks.rb, line 84
def _define_callbacks_and_wrap_original_method(name)
  if !self.class_variable_defined?(:@@methods_to_redefine)
    self.class_eval do
      mattr_accessor :methods_to_redefine
      self.methods_to_redefine = []
    end
  end
  self.methods_to_redefine << name

  self.class_eval { define_model_callbacks name }
  _define_method_with_callbacks(name)
  _redefine_original_method(name)
end
_define_method_with_callbacks(name) click to toggle source
# File lib/ardm/ar/hooks.rb, line 72
def _define_method_with_callbacks(name)
  self.class_eval do
    unless method_defined?(_callbacks_method(name))
      define_method(_callbacks_method(name)) do |*args|
        run_callbacks(name) do
          self.send(self.class._original_method(name), *args)
        end
      end
    end
  end
end
_original_method(name) click to toggle source
# File lib/ardm/ar/hooks.rb, line 68
def _original_method(name)
  "_original_#{name}".to_sym
end
_redefine_original_method(name) click to toggle source
# File lib/ardm/ar/hooks.rb, line 55
def _redefine_original_method(name)
  self.class_eval do
    if method_defined?(name) && instance_method(name) != instance_method(_callbacks_method(name))
      alias_method _original_method(name), name
      alias_method name, _callbacks_method(name)
    end
  end
end
after(event, meth=nil, &block) click to toggle source
# File lib/ardm/ar/hooks.rb, line 34
def after(event, meth=nil, &block)
  _ardm_hook(:after, event, meth, &block)
end
before(event, meth=nil, &block) click to toggle source
# File lib/ardm/ar/hooks.rb, line 30
def before(event, meth=nil, &block)
  _ardm_hook(:before, event, meth, &block)
end