public
Description: A Ruby On Rails plugin that enables the temporary disabling of ActiveRecord callbacks
Homepage: http://www.brentmc79.com/without_callbacks
Clone URL: git://github.com/brentmc79/without_callbacks.git
100644 85 lines (55 sloc) 1.934 kb
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
WithoutCallbacks
================
 
ActiveRecord callbacks can be extremely useful, but sometimes they
just get in the way. Wouldn't it be nice if you could disable the
callbacks at will? Well, now you can!
 
 
 
Example
=======
 
Given an AR model like so:
 
class ShamWowGuy < ActiveRecord::Base
before_save :slap_chop
before_update :punch_hooker
private
def punch_hooker
self.hooker_count = hooker_count+1
end
def slap_chop
self.catchphrase = "You're gonna love my nuts!"
end
end
 
What happens when you create/save the model?
 
vince = ShamWowGuy.new(:catchphrase => "You'll say WOW every time!")
vince.save
vince.catchphrase #=> "You're gonna love my nuts!"
 
When the model is saved, its catchphrase attribute is updated by the
callback just prior to being persisted to the database.
 
Maybe your Mom came by for a visit and you don't really want Vince,
the ShamWow guy, blurting offensive comments about his nuts. Well,
here's what you do:
 
vince = ShamWowGuy.new(:catchphrase => "You'll say WOW evey time!")
ShamWowGuy.without_callbacks(:slap_chop) do
vince.save
end
vince.catchphrase #=> "You'll say WOW evey time!"
 
Uh-oh, there's a typo in our catchphrase, so we need to update
vince. Mom's still here and she doesn't approve of hooker-punching.
What's a girl to do?
 
We can pass in both callback method names, like so:
 
ShamWowGuy.without_callbacks(:slap_chop, :punch_hooker) do
vince.save
end
 
Or, we can disable ALL callbacks by not passing any arguments:
 
ShamWowGuy.without_callbacks do
vince.save
end
 
That's all there is to it!
 
 
 
Note
====
 
At the moment, without_callbacks only disables instance methods
defined within the specified class. Procs or eval'd strings
like this:
 
before_save {|sham_wow_guy| sham_wow_guy.slap_chop }
 
OR
 
before_update 'self.hooker_count = nil'
 
in the callback class methods are not yet handled.
 
 
 
 
Copyright (c) 2009 Brent Collier, released under the MIT license