steipete_is_paranoid 0.9.6

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,4 @@
1
+ is_paranoid.db
2
+ pkg
3
+ *.gem
4
+ doc/
@@ -0,0 +1,43 @@
1
+ This will only document major changes. Please see the commit log for minor changes.
2
+
3
+ -2009-09-25
4
+ * fixing bug with has_many :through not respecting is_paranoid conditions (thanks, Ben Johnson)
5
+
6
+ -2009-09-18
7
+ * making is_paranoid play nice with habtm relationships
8
+
9
+ -2009-09-17
10
+ * fixed when primary key was not "id" (ie: "uuid") via Thibaud Guillaume-Gentil
11
+
12
+ -2009-09-15
13
+ * added support for has_many associations (i.e. @r2d2.components_with_destroyed) via Amiel Martin
14
+
15
+ -2009-06-13
16
+ * added support for is_paranoid conditions being maintained on preloaded associations
17
+ * destroy and restore now return self (to be more in keeping with other ActiveRecord methods) via Brent Dillingham
18
+
19
+ -2009-05-19
20
+ * added support for specifying relationships to restore via instance_model.restore(:include => [:parent_1, :child_1, :child_2]), etc.
21
+ * method_missing is no longer overridden on instances provided you declare your custom method_missing *before* specifying the model is_paranoid
22
+
23
+ -2009-05-12
24
+ * added support for parent_with_destroyed methods
25
+
26
+ -2009-04-27
27
+ * restoring models now cascades to child dependent => destroy models via Matt Todd
28
+
29
+ -2009-04-22
30
+ * destroying and restoring records no longer triggers saving/updating callbacks
31
+
32
+ -2009-03-28
33
+ * removing syntax for calculation require (all find and ActiveRecord calculations are done on-the-fly now via method_missing)
34
+ * adding ability to specify alternate fields and values for destroyed objects
35
+ * adding in support for _destroyed_only methods (with inspiration from David Krmpotic)
36
+ * adding init.rb via David Krmpotic
37
+ * adding jewler tasks via Scott Woods
38
+
39
+ -2009-03-24
40
+ * requiring specific syntax to include calculations
41
+
42
+ -2009-03-21
43
+ * initial release
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2009 Jeffrey Chupp
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
@@ -0,0 +1,113 @@
1
+ h1. is_paranoid ( same as it ever was )
2
+
3
+ h3. advice and disclaimer
4
+
5
+ You should always declare is_paranoid before any associations in your model unless you have a good reason for doing otherwise. Some relationships might not behave properly if you fail to do so. If you know what you're doing (and have written tests) and want to supress the warning then you can pass :suppress_load_order_warning => true as an option.
6
+
7
+ <pre>
8
+ is_paranoid :suppress_load_order_warning => true
9
+ </pre>
10
+
11
+ You should never expect _any_ library to work or behave exactly how you want it to: test, test, test and file an issue if you have any problems. Bonus points if you include sample failing code. Extra bonus points if you send a pull request that implements a feature/fixes a bug.
12
+
13
+ h3. and you may ask yourself, well, how did I get here?
14
+
15
+ Sometimes you want to delete something in ActiveRecord, but you realize you might need it later (for an undo feature, or just as a safety net, etc.). There are a plethora of plugins that accomplish this, the most famous of which is the venerable acts_as_paranoid which is great but not really actively developed any more. What's more, acts_as_paranoid was written for an older version of ActiveRecord and, with default_scope in 2.3, it is now possible to do the same thing with significantly less complexity. Thus, *is_paranoid*.
16
+
17
+ h3. and you may ask yourself, how do I work this?
18
+
19
+ You should read the specs, or the RDOC, or even the source itself (which is very readable), but for the lazy, here's the hand-holding:
20
+
21
+ You need ActiveRecord 2.3 and you need to properly install this gem. Then you need a model with a field to serve as a flag column on its database table. For this example we'll use a timestamp named "deleted_at". If that column is null, the item isn't deleted. If it has a timestamp, it should count as deleted.
22
+
23
+ So let's assume we have a model Automobile that has a deleted_at column on the automobiles table.
24
+
25
+ If you're working with Rails, in your environment.rb, add the following to your initializer block (you may want to change the version number).
26
+
27
+ <pre>
28
+ Rails::Initializer.run do |config|
29
+ # ...
30
+ config.gem "semanticart-is_paranoid", :lib => 'is_paranoid', :version => ">= 0.0.1"
31
+ end
32
+ </pre>
33
+
34
+ Then in your ActiveRecord model
35
+
36
+ <pre>
37
+ class Automobile < ActiveRecord::Base
38
+ is_paranoid
39
+ end
40
+ </pre>
41
+
42
+ Now our automobiles are now soft-deleteable.
43
+
44
+ <pre>
45
+ that_large_automobile = Automobile.create()
46
+ Automobile.count # => 1
47
+
48
+ that_large_automobile.destroy
49
+ Automobile.count # => 0
50
+ Automobile.count_with_destroyed # => 1
51
+
52
+ # where is that large automobile?
53
+ that_large_automobile = Automobile.find_with_destroyed(:all).first
54
+ that_large_automobile.restore
55
+ Automobile.count # => 1
56
+ </pre>
57
+
58
+ One thing to note, destroying is always undo-able, but deleting is not. This is a behavior difference between acts_as_paranoid and is_paranoid.
59
+
60
+ <pre>
61
+ Automobile.destroy_all
62
+ Automobile.count # => 0
63
+ Automobile.count_with_destroyed # => 1
64
+
65
+ Automobile.delete_all
66
+ Automobile.count_with_destroyed # => 0
67
+ # And you may say to yourself, "My god! What have I done?"
68
+ </pre>
69
+
70
+ All calculations and finds are created via a define_method call in method_missing. So you don't get a bunch of unnecessary methods defined unless you use them. Any find/count/sum/etc. _with_destroyed calls should work and you can also do find/count/sum/etc._destroyed_only.
71
+
72
+ h3. Specifying alternate rules for what should be considered destroyed
73
+
74
+ "deleted_at" as a timestamp is what acts_as_paranoid uses to define what is and isn't destroyed (see above), but you can specify alternate options with is_paranoid. In the is_paranoid line of your model you can specify the field, the value the field should have if the entry should count as destroyed, and the value the field should have if the entry is not destroyed. Consider the following models:
75
+
76
+ <pre>
77
+ class Pirate < ActiveRecord::Base
78
+ is_paranoid :field => [:alive, false, true]
79
+ end
80
+
81
+ class DeadPirate < ActiveRecord::Base
82
+ set_table_name :pirates
83
+ is_paranoid :field => [:alive, true, false]
84
+ end
85
+ </pre>
86
+
87
+ These two models share the same table, but when we are finding Pirates, we're only interested in those that are alive. To break it down, we specify :alive as our field to check, false as what the model field should be marked at when destroyed and true to what the field should be if they're not destroyed. DeadPirates are specified as the opposite. Check out the specs if you're still confused.
88
+
89
+ h3. Note about validates_uniqueness_of:
90
+
91
+ validates_uniqueness_of does not, by default, ignore items marked with a deleted_at (or other field name) flag. This is a behavior difference between is_paranoid and acts_as_paranoid. You can overcome this by specifying the field name you are using to mark destroyed items as your scope. Example:
92
+
93
+ <pre>
94
+ class Android < ActiveRecord::Base
95
+ validates_uniqueness_of :name, :scope => :deleted_at
96
+ is_paranoid
97
+ end
98
+ </pre>
99
+
100
+ And now the validates_uniqueness_of will ignore items that are destroyed.
101
+
102
+ h3. and you may ask yourself, where does that highway go to?
103
+
104
+ If you find any bugs, have any ideas of features you think are missing, or find things you're like to see work differently, feel free to file an issue or send a pull request.
105
+
106
+ Currently on the todo list:
107
+ * add options for merging additional default_scope options (i.e. order, etc.)
108
+
109
+ h3. Thanks
110
+
111
+ Thanks to Rick Olson for acts_as_paranoid which is obviously an inspiration in concept and execution, Ryan Bates for mentioning the idea of using default_scope for this on Ryan Daigle's "post introducing default_scope":defscope, and the Talking Heads for being the Talking Heads.
112
+
113
+ [defscope]http://ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping
@@ -0,0 +1,24 @@
1
+ require "spec"
2
+ require "spec/rake/spectask"
3
+ require 'lib/is_paranoid.rb'
4
+
5
+ Spec::Rake::SpecTask.new do |t|
6
+ t.spec_opts = ['--options', "\"#{File.dirname(__FILE__)}/spec/spec.opts\""]
7
+ t.spec_files = FileList['spec/**/*_spec.rb']
8
+ end
9
+
10
+ begin
11
+ require 'jeweler'
12
+ Jeweler::Tasks.new do |s|
13
+ s.name = %q{is_paranoid}
14
+ s.summary = %q{ActiveRecord 2.3 compatible gem "allowing you to hide and restore records without actually deleting them." Yes, like acts_as_paranoid, only with less code and less complexity.}
15
+ s.email = %q{jeff@semanticart.com}
16
+ s.homepage = %q{http://github.com/jchupp/is_paranoid/}
17
+ s.description = ""
18
+ s.authors = ["Jeffrey Chupp"]
19
+ end
20
+ rescue LoadError
21
+ puts "Jeweler not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com"
22
+ end
23
+
24
+ task :default => :spec
@@ -0,0 +1,4 @@
1
+ ---
2
+ :patch: 6
3
+ :major: 0
4
+ :minor: 9
data/init.rb ADDED
@@ -0,0 +1 @@
1
+ require 'is_paranoid'
@@ -0,0 +1,56 @@
1
+ # Generated by jeweler
2
+ # DO NOT EDIT THIS FILE
3
+ # Instead, edit Jeweler::Tasks in Rakefile, and run `rake gemspec`
4
+ # -*- encoding: utf-8 -*-
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = %q{steipete_is_paranoid}
8
+ s.version = "0.9.6"
9
+
10
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
+ s.authors = ["Jeffrey Chupp", "Peter Steinberger"]
12
+ s.date = %q{2009-09-26}
13
+ s.description = %q{}
14
+ s.email = %q{jeff@semanticart.com}
15
+ s.extra_rdoc_files = [
16
+ "README.textile"
17
+ ]
18
+ s.files = [
19
+ ".gitignore",
20
+ "CHANGELOG",
21
+ "MIT-LICENSE",
22
+ "README.textile",
23
+ "Rakefile",
24
+ "VERSION.yml",
25
+ "init.rb",
26
+ "is_paranoid.gemspec",
27
+ "lib/is_paranoid.rb",
28
+ "spec/database.yml",
29
+ "spec/is_paranoid_spec.rb",
30
+ "spec/models.rb",
31
+ "spec/schema.rb",
32
+ "spec/spec.opts",
33
+ "spec/spec_helper.rb"
34
+ ]
35
+ s.homepage = %q{http://github.com/jchupp/is_paranoid/}
36
+ s.rdoc_options = ["--charset=UTF-8"]
37
+ s.require_paths = ["lib"]
38
+ s.rubygems_version = %q{1.3.5}
39
+ s.summary = %q{ActiveRecord 2.3 compatible gem "allowing you to hide and restore records without actually deleting them." Yes, like acts_as_paranoid, only with less code and less complexity.}
40
+ s.test_files = [
41
+ "spec/is_paranoid_spec.rb",
42
+ "spec/models.rb",
43
+ "spec/schema.rb",
44
+ "spec/spec_helper.rb"
45
+ ]
46
+
47
+ if s.respond_to? :specification_version then
48
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
49
+ s.specification_version = 3
50
+
51
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
52
+ else
53
+ end
54
+ else
55
+ end
56
+ end
@@ -0,0 +1,275 @@
1
+ require 'activerecord'
2
+
3
+ module IsParanoid
4
+ # Call this in your model to enable all the safety-net goodness
5
+ #
6
+ # Example:
7
+ #
8
+ # class Android < ActiveRecord::Base
9
+ # is_paranoid
10
+ # end
11
+ #
12
+
13
+ def is_paranoid opts = {}
14
+ opts[:field] ||= [:deleted_at, Proc.new{Time.now.utc}, nil]
15
+ class_inheritable_accessor :destroyed_field, :field_destroyed, :field_not_destroyed
16
+ self.destroyed_field, self.field_destroyed, self.field_not_destroyed = opts[:field]
17
+
18
+ if self.reflect_on_all_associations.size > 0 && ! opts[:suppress_load_order_warning]
19
+ warn "is_paranoid warning in class #{self}: You should declare is_paranoid before your associations"
20
+ end
21
+
22
+ # This is the real magic. All calls made to this model will append
23
+ # the conditions deleted_at => nil (or whatever your destroyed_field
24
+ # and field_not_destroyed are). All exceptions require using
25
+ # exclusive_scope (see self.delete_all, self.count_with_destroyed,
26
+ # and self.find_with_destroyed defined in the module ClassMethods)
27
+ default_scope :conditions => {destroyed_field => field_not_destroyed}
28
+
29
+ extend ClassMethods
30
+ include InstanceMethods
31
+ end
32
+
33
+ module ClassMethods
34
+ def is_or_equals_not_destroyed
35
+ if [nil, 'NULL'].include?(field_not_destroyed)
36
+ 'IS NULL'
37
+ else
38
+ "= #{field_not_destroyed}"
39
+ end
40
+ end
41
+
42
+ # ensure that we respect the is_paranoid conditions when being loaded as a has_many :through
43
+ # NOTE: this only works if is_paranoid is declared before has_many relationships.
44
+ def has_many(association_id, options = {}, &extension)
45
+ if options.key?(:through)
46
+ conditions = "#{options[:through].to_s.pluralize}.#{destroyed_field} #{is_or_equals_not_destroyed}"
47
+ options[:conditions] = "(" + [options[:conditions], conditions].compact.join(") AND (") + ")"
48
+ end
49
+ super
50
+ end
51
+
52
+
53
+ # Actually delete the model, bypassing the safety net. Because
54
+ # this method is called internally by Model.delete(id) and on the
55
+ # delete method in each instance, we don't need to specify those
56
+ # methods separately
57
+ def delete_all conditions = nil
58
+ self.with_exclusive_scope { super conditions }
59
+ end
60
+
61
+ # Use update_all with an exclusive scope to restore undo the soft-delete.
62
+ # This bypasses update-related callbacks.
63
+ #
64
+ # By default, restores cascade through associations that are belongs_to
65
+ # :dependent => :destroy and under is_paranoid. You can prevent restoration
66
+ # of associated models by passing :include_destroyed_dependents => false,
67
+ # for example:
68
+ #
69
+ # Android.restore(:include_destroyed_dependents => false)
70
+ #
71
+ # Alternatively you can specify which relationships to restore via :include,
72
+ # for example:
73
+ #
74
+ # Android.restore(:include => [:parts, memories])
75
+ #
76
+ # Please note that specifying :include means you're not using
77
+ # :include_destroyed_dependents by default, though you can explicitly use
78
+ # both if you want all has_* relationships and specific belongs_to
79
+ # relationships, for example
80
+ #
81
+ # Android.restore(:include => [:home, :planet], :include_destroyed_dependents => true)
82
+ def restore(id, options = {})
83
+ options.reverse_merge!({:include_destroyed_dependents => true}) unless options[:include]
84
+ with_exclusive_scope do
85
+ update_all(
86
+ "#{destroyed_field} = #{connection.quote(field_not_destroyed)}",
87
+ primary_key.to_sym => id
88
+ )
89
+ end
90
+
91
+ self.reflect_on_all_associations.each do |association|
92
+ if association.options[:dependent] == :destroy and association.klass.respond_to?(:restore)
93
+ dependent_relationship = association.macro.to_s =~ /^has/
94
+ if should_restore?(association.name, dependent_relationship, options)
95
+ if dependent_relationship
96
+ restore_related(association.klass, association.primary_key_name, id, options)
97
+ else
98
+ restore_related(
99
+ association.klass,
100
+ association.klass.primary_key,
101
+ self.first(id).send(association.primary_key_name),
102
+ options
103
+ )
104
+ end
105
+ end
106
+ end
107
+ end
108
+ end
109
+
110
+ # TODO: needs better implementation
111
+ def exists_with_destroyed id
112
+ self.with_exclusive_scope{ exists?(id)}
113
+ end
114
+
115
+ # find_with_destroyed and other blah_with_destroyed and
116
+ # blah_destroyed_only methods are defined here
117
+ def method_missing name, *args, &block
118
+ if name.to_s =~ /^(.*)(_destroyed_only|_with_destroyed)$/ and self.respond_to?($1)
119
+ self.extend(Module.new{
120
+ if $2 == '_with_destroyed'
121
+ # Example:
122
+ # def count_with_destroyed(*args)
123
+ # self.with_exclusive_scope{ self.send(:count, *args) }
124
+ # end
125
+ define_method name do |*args|
126
+ self.with_exclusive_scope{ self.send($1, *args) }
127
+ end
128
+ else
129
+
130
+ # Example:
131
+ # def count_destroyed_only(*args)
132
+ # self.with_exclusive_scope do
133
+ # with_scope({:find => { :conditions => ["#{destroyed_field} IS NOT ?", nil] }}) do
134
+ # self.send(:count, *args)
135
+ # end
136
+ # end
137
+ # end
138
+ define_method name do |*args|
139
+ self.with_exclusive_scope do
140
+ with_scope({:find => { :conditions => ["#{self.table_name}.#{destroyed_field} IS NOT ?", field_not_destroyed] }}) do
141
+ self.send($1, *args, &block)
142
+ end
143
+ end
144
+ end
145
+
146
+ end
147
+ })
148
+ self.send(name, *args, &block)
149
+ else
150
+ super(name, *args, &block)
151
+ end
152
+ end
153
+
154
+ # with_exclusive_scope is used internally by ActiveRecord when preloading
155
+ # associations. Unfortunately this is problematic for is_paranoid since we
156
+ # want preloaded is_paranoid items to still be scoped to their deleted conditions.
157
+ # so we override that here.
158
+ def with_exclusive_scope(method_scoping = {}, &block)
159
+ # this is rather hacky, suggestions for improvements appreciated... the idea
160
+ # is that when the caller includes the method preload_associations, we want
161
+ # to apply our is_paranoid conditions
162
+ if caller.any?{|c| c =~ /\d+:in `preload_associations'$/}
163
+ method_scoping.deep_merge!(:find => {:conditions => {destroyed_field => field_not_destroyed} })
164
+ end
165
+ super method_scoping, &block
166
+ end
167
+
168
+ protected
169
+
170
+ def should_restore?(association_name, dependent_relationship, options) #:nodoc:
171
+ ([*options[:include]] || []).include?(association_name) or
172
+ (options[:include_destroyed_dependents] and dependent_relationship)
173
+ end
174
+
175
+ def restore_related klass, key_name, id, options #:nodoc:
176
+ klass.find_destroyed_only(:all,
177
+ :conditions => ["#{key_name} = ?", id]
178
+ ).each do |model|
179
+ model.restore(options)
180
+ end
181
+ end
182
+ end
183
+
184
+ module InstanceMethods
185
+ def destroyed?
186
+ destroyed_field != nil
187
+ end
188
+
189
+ def self.included(base)
190
+ base.class_eval do
191
+ unless method_defined? :method_missing
192
+ def method_missing(meth, *args, &block); super; end
193
+ end
194
+ alias_method :old_method_missing, :method_missing
195
+ alias_method :method_missing, :is_paranoid_method_missing
196
+ end
197
+ end
198
+
199
+ def is_paranoid_method_missing name, *args, &block
200
+ # if we're trying for a _____with_destroyed method
201
+ # and we can respond to the _____ method
202
+ # and we have an association by the name of _____
203
+ if name.to_s =~ /^(.*)(_with_destroyed)$/ and
204
+ self.respond_to?($1) and
205
+ (assoc = self.class.reflect_on_all_associations.detect{|a| a.name.to_s == $1})
206
+
207
+ parent_klass = Object.module_eval("::#{assoc.class_name}", __FILE__, __LINE__)
208
+
209
+ self.class.send(
210
+ :include,
211
+ Module.new {
212
+ if assoc.macro.to_s =~ /^has/
213
+ parent_method = assoc.macro.to_s =~ /^has_one/ ? 'first_with_destroyed' : 'all_with_destroyed'
214
+ # Example:
215
+ define_method name do |*args| # def android_with_destroyed
216
+ parent_klass.send("#{parent_method}", # Android.all_with_destroyed(
217
+ :conditions => { # :conditions => {
218
+ assoc.primary_key_name => # :person_id =>
219
+ self.send(parent_klass.primary_key) # self.send(:id)
220
+ } # }
221
+ ) # )
222
+ end # end
223
+
224
+ else
225
+ # Example:
226
+ define_method name do |*args| # def android_with_destroyed
227
+ parent_klass.first_with_destroyed( # Android.first_with_destroyed(
228
+ :conditions => { # :conditions => {
229
+ parent_klass.primary_key => # :id =>
230
+ self.send(assoc.primary_key_name) # self.send(:android_id)
231
+ } # }
232
+ ) # )
233
+ end # end
234
+ end
235
+ }
236
+ )
237
+ self.send(name, *args, &block)
238
+ else
239
+ old_method_missing(name, *args, &block)
240
+ end
241
+ end
242
+
243
+ # Mark the model deleted_at as now.
244
+ def alt_destroy_without_callbacks
245
+ self.class.update_all(
246
+ "#{destroyed_field} = #{self.class.connection.quote(( field_destroyed.respond_to?(:call) ? field_destroyed.call : field_destroyed))}",
247
+ self.class.primary_key.to_sym => self.id
248
+ )
249
+ self
250
+ end
251
+
252
+ # Override the default destroy to allow us to flag deleted_at.
253
+ # This preserves the before_destroy and after_destroy callbacks.
254
+ # Because this is also called internally by Model.destroy_all and
255
+ # the Model.destroy(id), we don't need to specify those methods
256
+ # separately.
257
+ def destroy
258
+ return false if callback(:before_destroy) == false
259
+ result = alt_destroy_without_callbacks
260
+ callback(:after_destroy)
261
+ self
262
+ end
263
+
264
+ # Set deleted_at flag on a model to field_not_destroyed, effectively
265
+ # undoing the soft-deletion.
266
+ def restore(options = {})
267
+ self.class.restore(id, options)
268
+ self
269
+ end
270
+
271
+ end
272
+
273
+ end
274
+
275
+ ActiveRecord::Base.send(:extend, IsParanoid)
@@ -0,0 +1,3 @@
1
+ test:
2
+ :adapter: sqlite3
3
+ :database: is_paranoid.db
@@ -0,0 +1,319 @@
1
+ require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
2
+ require File.expand_path(File.dirname(__FILE__) + '/models')
3
+
4
+ LUKE = 'Luke Skywalker'
5
+
6
+ describe IsParanoid do
7
+ before(:each) do
8
+ Android.delete_all
9
+ Person.delete_all
10
+ Component.delete_all
11
+
12
+ @luke = Person.create(:name => LUKE)
13
+ @r2d2 = Android.create(:name => 'R2D2', :owner_id => @luke.id)
14
+ @c3p0 = Android.create(:name => 'C3P0', :owner_id => @luke.id)
15
+
16
+ @r2d2.components.create(:name => 'Rotors')
17
+
18
+ @r2d2.memories.create(:name => 'A pretty sunset')
19
+ @c3p0.sticker = Sticker.create(:name => 'OMG, PONIES!')
20
+ @tatooine = Place.create(:name => "Tatooine")
21
+ @r2d2.places << @tatooine
22
+ end
23
+
24
+ describe 'non-is_paranoid models' do
25
+ it "should destroy as normal" do
26
+ lambda{
27
+ @luke.destroy
28
+ }.should change(Person, :count).by(-1)
29
+
30
+ lambda{
31
+ Person.count_with_destroyed
32
+ }.should raise_error(NoMethodError)
33
+ end
34
+ end
35
+
36
+ describe 'destroying' do
37
+ it "should soft-delete a record" do
38
+ lambda{
39
+ Android.destroy(@r2d2.id)
40
+ }.should change(Android, :count).from(2).to(1)
41
+ Android.count_with_destroyed.should == 2
42
+ end
43
+
44
+ it "should not hit update/save related callbacks" do
45
+ lambda{
46
+ Android.first.update_attribute(:name, 'Robocop')
47
+ }.should raise_error
48
+
49
+ lambda{
50
+ Android.first.destroy
51
+ }.should_not raise_error
52
+ end
53
+
54
+ it "should soft-delete matching items on Model.destroy_all" do
55
+ lambda{
56
+ Android.destroy_all("owner_id = #{@luke.id}")
57
+ }.should change(Android, :count).from(2).to(0)
58
+ Android.count_with_destroyed.should == 2
59
+ end
60
+
61
+ describe 'related models' do
62
+ it "should no longer show up in the relationship to the owner" do
63
+ @luke.androids.size.should == 2
64
+ @r2d2.destroy
65
+ @luke.androids.size.should == 1
66
+ end
67
+
68
+ it "should soft-delete on dependent destroys" do
69
+ lambda{
70
+ @luke.destroy
71
+ }.should change(Android, :count).from(2).to(0)
72
+ Android.count_with_destroyed.should == 2
73
+ end
74
+
75
+ it "shouldn't have problems with has_many :through relationships" do
76
+ # TODO: this spec can be cleaner and more specific, replace it later
77
+ # Dings use a boolean non-standard is_paranoid field
78
+ # Scratch uses the defaults. Testing both ensures compatibility
79
+ [[:dings, Ding], [:scratches, Scratch]].each do |method, klass|
80
+ @r2d2.dings.should == []
81
+
82
+ dent = Dent.create(:description => 'really terrible', :android_id => @r2d2.id)
83
+ item = klass.create(:description => 'quite nasty', :dent_id => dent.id)
84
+ @r2d2.reload
85
+ @r2d2.send(method).should == [item]
86
+
87
+ dent.destroy
88
+ @r2d2.reload
89
+ @r2d2.send(method).should == []
90
+ end
91
+ end
92
+
93
+ it "should not choke has_and_belongs_to_many relationships" do
94
+ @r2d2.places.should include(@tatooine)
95
+ @tatooine.destroy
96
+ @r2d2.reload
97
+ @r2d2.places.should_not include(@tatooine)
98
+ Place.all_with_destroyed.should include(@tatooine)
99
+ end
100
+ end
101
+ end
102
+
103
+ describe 'finding destroyed models' do
104
+ it "should be able to find destroyed items via #find_with_destroyed" do
105
+ @r2d2.destroy
106
+ Android.find(:first, :conditions => {:name => 'R2D2'}).should be_blank
107
+ Android.first_with_destroyed(:conditions => {:name => 'R2D2'}).should_not be_blank
108
+ end
109
+
110
+ it "should be able to find only destroyed items via #find_destroyed_only" do
111
+ @r2d2.destroy
112
+ Android.all_destroyed_only.size.should == 1
113
+ Android.first_destroyed_only.should == @r2d2
114
+ end
115
+
116
+ it "should not show destroyed models via :include" do
117
+ Person.first(:conditions => {:name => LUKE}, :include => :androids).androids.size.should == 2
118
+ @r2d2.destroy
119
+ person = Person.first(:conditions => {:name => LUKE}, :include => :androids)
120
+ # ensure that we're using the preload and not loading it via a find
121
+ Android.should_not_receive(:find)
122
+ person.androids.size.should == 1
123
+ end
124
+ end
125
+
126
+ describe 'calculations' do
127
+ it "should have a proper count inclusively and exclusively of destroyed items" do
128
+ @r2d2.destroy
129
+ @c3p0.destroy
130
+ Android.count.should == 0
131
+ Android.count_with_destroyed.should == 2
132
+ end
133
+
134
+ it "should respond to various calculations" do
135
+ @r2d2.destroy
136
+ Android.sum('id').should == @c3p0.id
137
+ Android.sum_with_destroyed('id').should == @r2d2.id + @c3p0.id
138
+ Android.average_with_destroyed('id').should == (@r2d2.id + @c3p0.id) / 2.0
139
+ end
140
+ end
141
+
142
+ describe 'deletion' do
143
+ it "should actually remove records on #delete_all" do
144
+ lambda{
145
+ Android.delete_all
146
+ }.should change(Android, :count_with_destroyed).from(2).to(0)
147
+ end
148
+
149
+ it "should actually remove records on #delete" do
150
+ lambda{
151
+ Android.first.delete
152
+ }.should change(Android, :count_with_destroyed).from(2).to(1)
153
+ end
154
+ end
155
+
156
+ describe 'restore' do
157
+ it "should allow restoring soft-deleted items" do
158
+ @r2d2.destroy
159
+ lambda{
160
+ @r2d2.restore
161
+ }.should change(Android, :count).from(1).to(2)
162
+ end
163
+
164
+ it "should not hit update/save related callbacks" do
165
+ @r2d2.destroy
166
+
167
+ lambda{
168
+ @r2d2.update_attribute(:name, 'Robocop')
169
+ }.should raise_error
170
+
171
+ lambda{
172
+ @r2d2.restore
173
+ }.should_not raise_error
174
+ end
175
+
176
+ it "should restore dependent models when being restored by default" do
177
+ @r2d2.destroy
178
+ lambda{
179
+ @r2d2.restore
180
+ }.should change(Component, :count).from(0).to(1)
181
+ end
182
+
183
+ it "should provide the option to not restore dependent models" do
184
+ @r2d2.destroy
185
+ lambda{
186
+ @r2d2.restore(:include_destroyed_dependents => false)
187
+ }.should_not change(Component, :count)
188
+ end
189
+
190
+ it "should restore parent and child models specified via :include" do
191
+ sub_component = SubComponent.create(:name => 'part', :component_id => @r2d2.components.first.id)
192
+ @r2d2.destroy
193
+ SubComponent.first(:conditions => {:id => sub_component.id}).should be_nil
194
+ @r2d2.components.first.restore(:include => [:android, :sub_components])
195
+ SubComponent.first(:conditions => {:id => sub_component.id}).should_not be_nil
196
+ Android.find(@r2d2.id).should_not be_nil
197
+ end
198
+ end
199
+
200
+ describe 'validations' do
201
+ it "should not ignore destroyed items in validation checks unless scoped" do
202
+ # Androids are not validates_uniqueness_of scoped
203
+ @r2d2.destroy
204
+ lambda{
205
+ Android.create!(:name => 'R2D2')
206
+ }.should raise_error(ActiveRecord::RecordInvalid)
207
+
208
+ lambda{
209
+ # creating shouldn't raise an error
210
+ another_r2d2 = AndroidWithScopedUniqueness.create!(:name => 'R2D2')
211
+ # neither should destroying the second incarnation since the
212
+ # validates_uniqueness_of is only applied on create
213
+ another_r2d2.destroy
214
+ }.should_not raise_error
215
+ end
216
+ end
217
+
218
+ describe '(parent)_with_destroyed' do
219
+ it "should be able to access destroyed parents" do
220
+ # Memory is has_many with a non-default primary key
221
+ # Sticker is a has_one with a default primary key
222
+ [Memory, Sticker].each do |klass|
223
+ instance = klass.last
224
+ parent = instance.android
225
+ instance.android.destroy
226
+
227
+ # reload so the model doesn't remember the parent
228
+ instance.reload
229
+ instance.android.should == nil
230
+ instance.android_with_destroyed.should == parent
231
+ end
232
+ end
233
+
234
+ it "should be able to access destroyed children" do
235
+ comps = @r2d2.components
236
+ comps.to_s # I have no idea why this makes it pass, but hey, here it is
237
+ @r2d2.components.first.destroy
238
+ @r2d2.components_with_destroyed.should == comps
239
+ end
240
+
241
+ it "should return nil if no destroyed parent exists" do
242
+ sticker = Sticker.new(:name => 'Rainbows')
243
+ # because the default relationship works this way, i.e.
244
+ sticker.android.should == nil
245
+ sticker.android_with_destroyed.should == nil
246
+ end
247
+
248
+ it "should not break method_missing's defined before the is_paranoid call" do
249
+ # we've defined a method_missing on Sticker
250
+ # that changes the sticker name.
251
+ sticker = Sticker.new(:name => "Ponies!")
252
+ lambda{
253
+ sticker.some_crazy_method_that_we_certainly_do_not_respond_to
254
+ }.should change(sticker, :name).to(Sticker::MM_NAME)
255
+ end
256
+ end
257
+
258
+ describe 'alternate fields and field values' do
259
+ it "should properly function for boolean values" do
260
+ # ninjas are invisible by default. not being ninjas, we can only
261
+ # find those that are visible
262
+ ninja = Ninja.create(:name => 'Esteban', :visible => true)
263
+ ninja.vanish # aliased to destroy
264
+ Ninja.first.should be_blank
265
+ Ninja.find_with_destroyed(:first).should == ninja
266
+ Ninja.count.should == 0
267
+
268
+ # we're only interested in pirates who are alive by default
269
+ pirate = Pirate.create(:name => 'Reginald')
270
+ pirate.destroy
271
+ Pirate.first.should be_blank
272
+ Pirate.find_with_destroyed(:first).should == pirate
273
+ Pirate.count.should == 0
274
+
275
+ # we're only interested in pirates who are dead by default.
276
+ # zombie pirates ftw!
277
+ DeadPirate.first.id.should == pirate.id
278
+ lambda{
279
+ DeadPirate.first.destroy
280
+ }.should change(Pirate, :count).from(0).to(1)
281
+ DeadPirate.count.should == 0
282
+ end
283
+ end
284
+
285
+ describe 'after_destroy and before_destroy callbacks' do
286
+ it "should rollback if before_destroy fails" do
287
+ edward = UndestroyablePirate.create(:name => 'Edward')
288
+ lambda{
289
+ edward.destroy
290
+ }.should_not change(UndestroyablePirate, :count)
291
+ end
292
+
293
+ it "should rollback if after_destroy raises an error" do
294
+ raul = RandomPirate.create(:name => 'Raul')
295
+ lambda{
296
+ begin
297
+ raul.destroy
298
+ rescue => ex
299
+ ex.message.should == 'after_destroy works'
300
+ end
301
+ }.should_not change(RandomPirate, :count)
302
+ end
303
+
304
+ it "should handle callbacks normally assuming no failures are encountered" do
305
+ component = Component.first
306
+ lambda{
307
+ component.destroy
308
+ }.should change(component, :name).to(Component::NEW_NAME)
309
+ end
310
+
311
+ end
312
+
313
+ describe "alternate primary key" do
314
+ it "should destroy without problem" do
315
+ uuid = Uuid.create(:name => "foo")
316
+ uuid.destroy.should be_true
317
+ end
318
+ end
319
+ end
@@ -0,0 +1,132 @@
1
+ class Person < ActiveRecord::Base #:nodoc:
2
+ validates_uniqueness_of :name
3
+ has_many :androids, :foreign_key => :owner_id, :dependent => :destroy
4
+ end
5
+
6
+ class Android < ActiveRecord::Base #:nodoc:
7
+ is_paranoid
8
+ validates_uniqueness_of :name
9
+ has_many :components, :dependent => :destroy
10
+ has_one :sticker
11
+ has_many :memories, :foreign_key => 'parent_id'
12
+ has_many :dents
13
+ has_many :dings, :through => :dents
14
+ has_many :scratches, :through => :dents
15
+ has_and_belongs_to_many :places
16
+
17
+ # this code is to ensure that our destroy and restore methods
18
+ # work without triggering before/after_update callbacks
19
+ before_update :raise_hell
20
+ def raise_hell
21
+ raise "hell"
22
+ end
23
+ end
24
+
25
+ class Dent < ActiveRecord::Base #:nodoc:
26
+ is_paranoid
27
+ belongs_to :android
28
+ has_many :dings
29
+ has_many :scratches
30
+ end
31
+
32
+ class Ding < ActiveRecord::Base #:nodoc:
33
+ is_paranoid :field => [:not_deleted, true, false]
34
+ belongs_to :dent
35
+ end
36
+
37
+ class Scratch < ActiveRecord::Base #:nodoc:
38
+ is_paranoid
39
+ belongs_to :dent
40
+ end
41
+
42
+ class Component < ActiveRecord::Base #:nodoc:
43
+ is_paranoid
44
+ belongs_to :android, :dependent => :destroy
45
+ has_many :sub_components, :dependent => :destroy
46
+ NEW_NAME = 'Something Else!'
47
+
48
+ after_destroy :change_name
49
+ def change_name
50
+ self.update_attribute(:name, NEW_NAME)
51
+ end
52
+ end
53
+
54
+ class SubComponent < ActiveRecord::Base #:nodoc:
55
+ is_paranoid
56
+ belongs_to :component, :dependent => :destroy
57
+ end
58
+
59
+ class Memory < ActiveRecord::Base #:nodoc:
60
+ is_paranoid
61
+ belongs_to :android, :class_name => "Android", :foreign_key => "parent_id"
62
+ end
63
+
64
+ class Sticker < ActiveRecord::Base #:nodoc:
65
+ MM_NAME = "You've got method_missing"
66
+
67
+ # this simply serves to ensure that we don't break method_missing
68
+ # if it is implemented on a class and called before is_paranoid
69
+ def method_missing name, *args, &block
70
+ self.name = MM_NAME
71
+ end
72
+
73
+ is_paranoid
74
+ belongs_to :android
75
+ end
76
+
77
+ class AndroidWithScopedUniqueness < ActiveRecord::Base #:nodoc:
78
+ set_table_name :androids
79
+ validates_uniqueness_of :name, :scope => :deleted_at
80
+ is_paranoid
81
+ end
82
+
83
+ class Place < ActiveRecord::Base #:nodoc:
84
+ is_paranoid
85
+ has_and_belongs_to_many :androids
86
+ end
87
+
88
+ class AndroidsPlaces < ActiveRecord::Base #:nodoc:
89
+ end
90
+
91
+ class Ninja < ActiveRecord::Base #:nodoc:
92
+ validates_uniqueness_of :name, :scope => :visible
93
+ is_paranoid :field => [:visible, false, true]
94
+
95
+ alias_method :vanish, :destroy
96
+ end
97
+
98
+ class Pirate < ActiveRecord::Base #:nodoc:
99
+ is_paranoid :field => [:alive, false, true]
100
+ end
101
+
102
+ class DeadPirate < ActiveRecord::Base #:nodoc:
103
+ set_table_name :pirates
104
+ is_paranoid :field => [:alive, true, false]
105
+ end
106
+
107
+ class RandomPirate < ActiveRecord::Base #:nodoc:
108
+ set_table_name :pirates
109
+
110
+ def after_destroy
111
+ raise 'after_destroy works'
112
+ end
113
+ end
114
+
115
+ class UndestroyablePirate < ActiveRecord::Base #:nodoc:
116
+ set_table_name :pirates
117
+ is_paranoid :field => [:alive, false, true]
118
+
119
+ def before_destroy
120
+ false
121
+ end
122
+ end
123
+
124
+ class Uuid < ActiveRecord::Base #:nodoc:
125
+ set_primary_key "uuid"
126
+
127
+ def before_create
128
+ self.uuid = "295b3430-85b8-012c-cfe4-002332cf7d5e"
129
+ end
130
+
131
+ is_paranoid
132
+ end
@@ -0,0 +1,86 @@
1
+ ActiveRecord::Schema.define(:version => 20090317164830) do
2
+ create_table "androids", :force => true do |t|
3
+ t.string "name"
4
+ t.integer "owner_id"
5
+ t.datetime "deleted_at"
6
+ t.datetime "created_at"
7
+ t.datetime "updated_at"
8
+ end
9
+
10
+ create_table "dents", :force => true do |t|
11
+ t.integer "android_id"
12
+ t.string "description"
13
+ t.datetime "deleted_at"
14
+ end
15
+
16
+ create_table "dings", :force => true do |t|
17
+ t.integer "dent_id"
18
+ t.string "description"
19
+ t.boolean "not_deleted"
20
+ end
21
+
22
+ create_table "scratches", :force => true do |t|
23
+ t.integer "dent_id"
24
+ t.string "description"
25
+ t.datetime "deleted_at"
26
+ end
27
+
28
+ create_table "androids_places", :force => true, :id => false do |t|
29
+ t.integer "android_id"
30
+ t.integer "place_id"
31
+ end
32
+
33
+ create_table "places", :force => true do |t|
34
+ t.string "name"
35
+ t.datetime "deleted_at"
36
+ end
37
+
38
+ create_table "people", :force => true do |t|
39
+ t.string "name"
40
+ t.datetime "created_at"
41
+ t.datetime "updated_at"
42
+ end
43
+
44
+ create_table "components", :force => true do |t|
45
+ t.string "name"
46
+ t.integer "android_id"
47
+ t.datetime "deleted_at"
48
+ t.datetime "created_at"
49
+ t.datetime "updated_at"
50
+ end
51
+
52
+ create_table "sub_components", :force => true do |t|
53
+ t.string "name"
54
+ t.integer "component_id"
55
+ t.datetime "deleted_at"
56
+ end
57
+
58
+ create_table "memories", :force => true do |t|
59
+ t.string "name"
60
+ t.integer "parent_id"
61
+ t.datetime "deleted_at"
62
+ end
63
+
64
+ create_table "stickers", :force => true do |t|
65
+ t.string "name"
66
+ t.integer "android_id"
67
+ t.datetime "deleted_at"
68
+ end
69
+
70
+ create_table "ninjas", :force => true do |t|
71
+ t.string "name"
72
+ t.boolean "visible", :default => false
73
+ end
74
+
75
+ create_table "pirates", :force => true do |t|
76
+ t.string "name"
77
+ t.boolean "alive", :default => true
78
+ end
79
+
80
+ create_table "uuids", :id => false, :force => true do |t|
81
+ t.string "uuid", :limit => 36, :primary => true
82
+ t.string "name"
83
+ t.datetime "deleted_at"
84
+ end
85
+
86
+ end
@@ -0,0 +1 @@
1
+ --color
@@ -0,0 +1,14 @@
1
+ require 'rubygems'
2
+ require "#{File.dirname(__FILE__)}/../lib/is_paranoid"
3
+ require 'activerecord'
4
+ require 'yaml'
5
+ require 'spec'
6
+
7
+ def connect(environment)
8
+ conf = YAML::load(File.open(File.dirname(__FILE__) + '/database.yml'))
9
+ ActiveRecord::Base.establish_connection(conf[environment])
10
+ end
11
+
12
+ # Open ActiveRecord connection
13
+ connect('test')
14
+ load(File.dirname(__FILE__) + "/schema.rb")
metadata ADDED
@@ -0,0 +1,73 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: steipete_is_paranoid
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.9.6
5
+ platform: ruby
6
+ authors:
7
+ - Jeffrey Chupp
8
+ - Peter Steinberger
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+
13
+ date: 2009-09-26 00:00:00 +02:00
14
+ default_executable:
15
+ dependencies: []
16
+
17
+ description: ""
18
+ email: jeff@semanticart.com
19
+ executables: []
20
+
21
+ extensions: []
22
+
23
+ extra_rdoc_files:
24
+ - README.textile
25
+ files:
26
+ - .gitignore
27
+ - CHANGELOG
28
+ - MIT-LICENSE
29
+ - README.textile
30
+ - Rakefile
31
+ - VERSION.yml
32
+ - init.rb
33
+ - is_paranoid.gemspec
34
+ - lib/is_paranoid.rb
35
+ - spec/database.yml
36
+ - spec/is_paranoid_spec.rb
37
+ - spec/models.rb
38
+ - spec/schema.rb
39
+ - spec/spec.opts
40
+ - spec/spec_helper.rb
41
+ has_rdoc: true
42
+ homepage: http://github.com/jchupp/is_paranoid/
43
+ licenses: []
44
+
45
+ post_install_message:
46
+ rdoc_options:
47
+ - --charset=UTF-8
48
+ require_paths:
49
+ - lib
50
+ required_ruby_version: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: "0"
55
+ version:
56
+ required_rubygems_version: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: "0"
61
+ version:
62
+ requirements: []
63
+
64
+ rubyforge_project:
65
+ rubygems_version: 1.3.5
66
+ signing_key:
67
+ specification_version: 3
68
+ summary: ActiveRecord 2.3 compatible gem "allowing you to hide and restore records without actually deleting them." Yes, like acts_as_paranoid, only with less code and less complexity.
69
+ test_files:
70
+ - spec/is_paranoid_spec.rb
71
+ - spec/models.rb
72
+ - spec/schema.rb
73
+ - spec/spec_helper.rb