forked from jnunemaker/user_stamp
-
Notifications
You must be signed in to change notification settings - Fork 1
/
user_stamp.rb
56 lines (45 loc) · 1.46 KB
/
user_stamp.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
module UserStamp
mattr_accessor :creator_attribute
mattr_accessor :updater_attribute
mattr_accessor :current_user_method
def self.creator_assignment_method
"#{UserStamp.creator_attribute}="
end
def self.updater_assignment_method
"#{UserStamp.updater_attribute}="
end
module ClassMethods
def user_stamp(*models)
models.each { |klass| klass.add_observer(UserStampSweeper.instance) }
class_eval do
cache_sweeper :user_stamp_sweeper
end
end
end
end
UserStamp.creator_attribute = :creator_id
UserStamp.updater_attribute = :updater_id
UserStamp.current_user_method = :current_user
class UserStampSweeper < ActionController::Caching::Sweeper
def before_destroy(record)
return unless current_user
if record.respond_to?(UserStamp.updater_assignment_method)
record.send(UserStamp.updater_assignment_method, current_user.id)
end
end
def before_validation(record)
return unless current_user
if record.respond_to?(UserStamp.creator_assignment_method) && record.new_record?
record.send(UserStamp.creator_assignment_method, current_user.id)
end
if record.respond_to?(UserStamp.updater_assignment_method)
record.send(UserStamp.updater_assignment_method, current_user.id)
end
end
private
def current_user
if controller.respond_to?(UserStamp.current_user_method)
controller.send UserStamp.current_user_method
end
end
end