Module: Ardm::Ar::Hooks::ClassMethods

Defined in:
lib/ardm/ar/hooks.rb

Instance Method Summary collapse

Instance Method Details

#_ardm_hook(order, event, meth = nil, &block) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 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) ⇒ Object



64
65
66
# 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) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
# 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) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
# 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) ⇒ Object



68
69
70
# File 'lib/ardm/ar/hooks.rb', line 68

def _original_method(name)
  "_original_#{name}".to_sym
end

#_redefine_original_method(name) ⇒ Object



55
56
57
58
59
60
61
62
# 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) ⇒ Object



34
35
36
# 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) ⇒ Object



30
31
32
# File 'lib/ardm/ar/hooks.rb', line 30

def before(event, meth=nil, &block)
  _ardm_hook(:before, event, meth, &block)
end