Module: Callbacks::ClassMethods

Defined in:
lib/classmethods.rb

Instance Method Summary collapse

Instance Method Details

#add_callback_action(type, method, *code, &block) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/classmethods.rb', line 62

def add_callback_action(type, method, *code, &block)
  ca = self.callback_actions
  
  ca[method] = {} if ca[method].nil?
  ca[method][type] = [] if ca[method][type].nil?
  
  if block_given?
    ca[method][type] << Callback.new(method, nil, &block)
  else
    code.each do |c|
      ca[method][type] << Callback.new(method, c)
    end
  end
end

#add_callback_methods(*callbacks) ⇒ Object



14
15
16
17
18
19
# File 'lib/classmethods.rb', line 14

def add_callback_methods(*callbacks)
  callbacks.each do |callback|
    self.callback_methods << callback.to_sym
    self.build_callback_method(callback)
  end
end

#build_callback_method(method) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/classmethods.rb', line 33

def build_callback_method(method)
    
  #instance_eval do
  instance_eval <<-"end_eval"

      def before_#{method}(*callbacks, &block)
        add_callback_action :before, :#{method}, *callbacks, &block
      end

      def after_#{method}(*callbacks, &block)
        add_callback_action :after, :#{method}, *callbacks, &block
      end

  end_eval
  #end
  
  class_eval <<-"end_eval"
    def #{method}_with_callbacks
      trigger_callback_actions(:#{method}, :before)
      retval = self.send("#{method}_without_callbacks")
      trigger_callback_actions(:#{method}, :after)
      return retval
    end
  end_eval
  
  send :alias_method, "#{method}_without_callbacks", method
  send :alias_method, method, "#{method}_with_callbacks"
end

#callback_actionsObject



9
10
11
12
# File 'lib/classmethods.rb', line 9

def callback_actions
  #Use one @, else it gets stored in the module and then it will be avaiable in every class that uses callback
  @callback_actions ||= {}
end

#callback_methodsObject



4
5
6
7
# File 'lib/classmethods.rb', line 4

def callback_methods
  #Use one @, else it gets stored in the module and then it will be avaiable in every class that uses callback
  @callback_methods ||= []
end

#remove_callback_method(method) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/classmethods.rb', line 21

def remove_callback_method(method)      
  self.meta_eval do
    remove_method("before_#{method}")
    remove_method("after_#{method}")
  end
  
  remove_method("#{method}_with_callbacks")
  remove_method(method) #This is the method_with_callbacks
  alias_method(method, "#{method}_without_callbacks")
  self.callback_methods.delete(method.to_sym)
end