-
Notifications
You must be signed in to change notification settings - Fork 1
/
hooks.rb
116 lines (87 loc) · 2.69 KB
/
hooks.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
require "pp"
require 'benchmark'
module EventMachine
module Hooks
EVENTS_DIR = "app/events"
def self.included(base)
class_eval <<-EOF
@@reporter_events = Array.new
EOF
base.class_eval <<-BCE
around_filter :reporter_around_filter
BCE
end
protected
def reporter_around_filter
events_load_bm = Benchmark.measure do
load_events if @@reporter_events.empty?
end
events = @@reporter_events.select {|e| e.match_event?(self.class, action_name)}
# Calling all before actions for this controler and action
events.each { |event| event.call_before(self) }
# Calling original action
yield
# Calling all after actions for this controler and action
events.each { |event| event.call_after(self) }
end
def for_action(controller, action, &block)
@@reporter_events << EventMeta.new(controller, action, &block)
end
def for_actions(actions_array, &block)
actions_array.each do |item|
@@reporter_events << EventMeta.new(item[0], item[1], &block)
end
end
def turn_off_for_action(controller, action, &block)
for_action(controller, action, &block) if test?
end
def load_events
return if test?
Dir["#{Rails.root + EVENTS_DIR}/**/*event.rb"].collect do |file|
load_event(file)
end
end
def load_event(file)
clear_events if test?
code = File.new(file).readlines.join('')
begin
instance_eval code, __FILE__, __LINE__
rescue => e
logger.warn "FAILED!"
logger.warn e.backtrace
end
end
def clear_events
@@reporter_events.clear
end
def reporter_events
@@reporter_events
end
def test?
ENV["RAILS_ENV"] == "test"
end
class EventMeta
def initialize(controller_class, name, &block)
@controller_class = controller_class
@action = name
self.instance_eval(&block)
end
def call_before(controller_instance)
controller_instance.instance_eval(&@before) if @before
end
def call_after(controller_instance)
controller_instance.instance_eval(&@after) if @after
end
def match_event?(clazz, action_name)
@controller_class == clazz && @action.to_s == action_name.to_s
end
private
def before(&block)
@before = block
end
def after(&block)
@after = block
end
end
end
end