cure_rails3_acts_as_paranoid 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2010 Gonçalo Silva
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,120 @@
1
+ # ActsAsParanoid
2
+
3
+ A simple plugin which hides records instead of deleting them, being able to recover them.
4
+
5
+ ## Credits
6
+
7
+ This plugin was inspired by [acts_as_paranoid](http://github.com/technoweenie/acts_as_paranoid) and [acts_as_active](http://github.com/fernandoluizao/acts_as_active).
8
+
9
+ While porting it to Rails 3, I decided to apply the ideas behind those plugins to an unified solution while removing a **lot** of the complexity found in them. I eventually ended up writing a new plugin from scratch.
10
+
11
+ ## Usage
12
+
13
+ You can enable ActsAsParanoid like this:
14
+
15
+ class Paranoiac < ActiveRecord::Base
16
+ acts_as_paranoid
17
+ end
18
+
19
+ ### Options
20
+
21
+ You can also specify the name of the column to store it's *deletion* and the type of data it holds:
22
+
23
+ - :column => 'deleted_at'
24
+ - :type => 'time'
25
+
26
+ The values shown are the defaults. While *column* can be anything (as long as it exists in your database), *type* is restricted to "boolean", "time" or "string".
27
+
28
+ If your column type is a "string", you can also specify which value to use when marking an object as deleted by passing `:deleted_value` (default is "deleted").
29
+
30
+ ### Filtering
31
+
32
+ If a record is deleted by ActsAsParanoid, it won't be retrieved when accessing the database. So, `Paranoiac.all` will **not** include the deleted_records. if you want to access them, you have 2 choices:
33
+
34
+ Paranoiac.only_deleted # retrieves the deleted records
35
+ Paranoiac.with_deleted # retrieves all records, deleted or not
36
+
37
+ ### Real deletion
38
+
39
+ In order to really delete a record, just use:
40
+
41
+ paranoiac.destroy!
42
+ Paranoiac.delete_all!(conditions)
43
+
44
+ You can also definitively delete a record by calling `destroy` or `delete_all` on it twice. If a record was already deleted (hidden by ActsAsParanoid) and you delete it again, it will be removed from the database. Take this example:
45
+
46
+ Paranoiac.first.destroy # does NOT delete the first record, just hides it
47
+ Paranoiac.only_deleted.destroy # deletes the first record from the database
48
+
49
+ ### Recovery
50
+
51
+ Recovery is easy. Just invoke `recover` on it, like this:
52
+
53
+ Paranoiac.only_deleted.where("name = ?", "not dead yet").first.recover
54
+
55
+ All associations marked as `:dependent => :destroy` are also recursively recovered. If you would like to disable this behavior, you can call `recover` with the `recursive` option:
56
+
57
+ Paranoiac.only_deleted.where("name = ?", "not dead yet").first.recover(:recursive => false)
58
+
59
+ If you would like to change the default behavior for a model, you can use the `recover_dependent_associations` option
60
+
61
+ class Paranoiac < ActiveRecord::Base
62
+ acts_as_paranoid :recover_dependent_associations => false
63
+ end
64
+
65
+ By default when using timestamp fields to mark deletion, dependent records will be recovered if they were deleted within 5 seconds of the object upon which they depend. This restores the objects to the state before the recursive deletion without restoring other objects that were deleted earlier. This window can be changed with the `dependent_recovery_window` option
66
+
67
+ class Paranoiac < ActiveRecord::Base
68
+ acts_as_paranoid
69
+ has_many :paranoids, :dependent => :destroy
70
+ end
71
+
72
+ class Paranoid < ActiveRecord::Base
73
+ belongs_to :paranoic
74
+
75
+ # Paranoid objects will be recovered alongside Paranoic objects
76
+ # if they were deleted within 1 minute of the Paranoic object
77
+ acts_as_paranoid :dependent_recovery_window => 1.minute
78
+ end
79
+
80
+ or in the recover statement
81
+
82
+ Paranoiac.only_deleted.where("name = ?", "not dead yet").first.recover(:recovery_window => 30.seconds)
83
+
84
+ ### Validation
85
+ ActiveRecord's built-in uniqueness validation does not account for records deleted by ActsAsParanoid. If you want to check for uniqueness among non-deleted records only, use the macro `validates_as_paranoid` in your model. Then, instead of using `validates_uniqueness_of`, use `validates_uniqueness_of_without_deleted`. This will keep deleted records from counting against the uniqueness check.
86
+
87
+ class Paranoiac < ActiveRecord::Base
88
+ acts_as_paranoid
89
+ validates_as_paranoid
90
+ validates_uniqueness_of_without_deleted :name
91
+ end
92
+
93
+ Paranoiac.create(:name => 'foo').destroy
94
+ Paranoiac.new(:name => 'foo').valid? #=> true
95
+
96
+
97
+ ### Status
98
+ Once you retrieve data using `with_deleted` scope you can check deletion status using `deleted?` helper:
99
+
100
+ Paranoiac.create(:name => 'foo').destroy
101
+ Paranoiac.with_deleted.first.deleted? #=> true
102
+
103
+ ## Caveats
104
+
105
+ Watch out for these caveats:
106
+
107
+ - You cannot use default\_scope in your model. It is possible to work around this caveat, but it's not pretty. Have a look at [this article](http://joshuaclayton.github.com/code/default_scope/activerecord/is_paranoid/multiple-default-scopes.html) if you really need to have your own default scope.
108
+ - You cannot use scopes named `with_deleted`, `only_deleted` and `paranoid_deleted_around_time`
109
+ - `unscoped` will return all records, deleted or not
110
+
111
+ ## Acknowledgements
112
+
113
+ * To [cheerfulstoic](https://github.com/cheerfulstoic) for adding recursive recovery
114
+ * To [Jonathan Vaught](https://github.com/gravelpup) for adding paranoid validations
115
+ * To [Geoffrey Hichborn](https://github.com/phene) for improving the overral code quality and adding support for after_commit
116
+ * To [flah00](https://github.com/flah00) for adding support for STI-based associations (with :dependent)
117
+ * To [vikramdhillon](https://github.com/vikramdhillon) for the idea and
118
+ initial implementation of support for string column type
119
+
120
+ Copyright © 2010 Gonçalo Silva, released under the MIT license
@@ -0,0 +1,199 @@
1
+ require 'active_record'
2
+ require 'validations/uniqueness_without_deleted'
3
+
4
+ module ActsAsParanoid
5
+
6
+ def paranoid?
7
+ self.included_modules.include?(InstanceMethods)
8
+ end
9
+
10
+ def validates_as_paranoid
11
+ extend ParanoidValidations::ClassMethods
12
+ end
13
+
14
+ def acts_as_paranoid(options = {})
15
+ raise ArgumentError, "Hash expected, got #{options.class.name}" if not options.is_a?(Hash) and not options.empty?
16
+
17
+ class_attribute :paranoid_configuration, :paranoid_column_reference
18
+
19
+ self.paranoid_configuration = { :column => "deleted_at", :column_type => "time", :recover_dependent_associations => true, :dependent_recovery_window => 2.minutes }
20
+ self.paranoid_configuration.merge!({ :deleted_value => "deleted" }) if options[:column_type] == "string"
21
+ self.paranoid_configuration.merge!(options) # user options
22
+
23
+ raise ArgumentError, "'time', 'boolean' or 'string' expected for :column_type option, got #{paranoid_configuration[:column_type]}" unless ['time', 'boolean', 'string'].include? paranoid_configuration[:column_type]
24
+
25
+ self.paranoid_column_reference = "#{self.table_name}.#{paranoid_configuration[:column]}"
26
+
27
+ return if paranoid?
28
+
29
+ ActiveRecord::Relation.class_eval do
30
+ alias_method :delete_all!, :delete_all
31
+ alias_method :destroy!, :destroy
32
+ end
33
+
34
+ # Magic!
35
+ default_scope where("#{paranoid_column_reference} IS ?", nil)
36
+
37
+ scope :paranoid_deleted_around_time, lambda {|value, window|
38
+ if self.class.respond_to?(:paranoid?) && self.class.paranoid?
39
+ if self.class.paranoid_column_type == 'time' && ![true, false].include?(value)
40
+ self.where("#{self.class.paranoid_column} > ? AND #{self.class.paranoid_column} < ?", (value - window), (value + window))
41
+ else
42
+ self.only_deleted
43
+ end
44
+ end if paranoid_configuration[:column_type] == 'time'
45
+ }
46
+
47
+ include InstanceMethods
48
+ extend ClassMethods
49
+ end
50
+
51
+ module ClassMethods
52
+ def self.extended(base)
53
+ base.define_callbacks :recover
54
+ end
55
+
56
+ def before_recover(method)
57
+ set_callback :recover, :before, method
58
+ end
59
+
60
+ def after_recover(method)
61
+ set_callback :recover, :after, method
62
+ end
63
+
64
+ def with_deleted
65
+ self.unscoped
66
+ end
67
+
68
+ def only_deleted
69
+ self.unscoped.where("#{paranoid_column_reference} IS NOT ?", nil)
70
+ end
71
+
72
+ def delete_all!(conditions = nil)
73
+ self.unscoped.delete_all!(conditions)
74
+ end
75
+
76
+ def delete_all(conditions = nil)
77
+ update_all ["#{paranoid_configuration[:column]} = ?", delete_now_value], conditions
78
+ end
79
+
80
+ def paranoid_column
81
+ paranoid_configuration[:column].to_sym
82
+ end
83
+
84
+ def paranoid_column_type
85
+ paranoid_configuration[:column_type].to_sym
86
+ end
87
+
88
+ def dependent_associations
89
+ self.reflect_on_all_associations.select {|a| [:destroy, :delete_all].include?(a.options[:dependent]) }
90
+ end
91
+
92
+ def delete_now_value
93
+ case paranoid_configuration[:column_type]
94
+ when "time" then Time.now
95
+ when "boolean" then true
96
+ when "string" then paranoid_configuration[:deleted_value]
97
+ end
98
+ end
99
+ end
100
+
101
+ module InstanceMethods
102
+
103
+ def paranoid_value
104
+ self.send(self.class.paranoid_column)
105
+ end
106
+
107
+ def destroy!
108
+ with_transaction_returning_status do
109
+ run_callbacks :destroy do
110
+ act_on_dependent_destroy_associations
111
+ self.class.delete_all!(self.class.primary_key.to_sym => self.id)
112
+ self.paranoid_value = self.class.delete_now_value
113
+ freeze
114
+ end
115
+ end
116
+ end
117
+
118
+ def destroy
119
+ if paranoid_value.nil?
120
+ with_transaction_returning_status do
121
+ run_callbacks :destroy do
122
+ self.class.delete_all(self.class.primary_key.to_sym => self.id)
123
+ self.paranoid_value = self.class.delete_now_value
124
+ self
125
+ end
126
+ end
127
+ else
128
+ destroy!
129
+ end
130
+ end
131
+
132
+ def recover(options={})
133
+ options = {
134
+ :recursive => self.class.paranoid_configuration[:recover_dependent_associations],
135
+ :recovery_window => self.class.paranoid_configuration[:dependent_recovery_window]
136
+ }.merge(options)
137
+
138
+ self.class.transaction do
139
+ run_callbacks :recover do
140
+ recover_dependent_associations(options[:recovery_window], options) if options[:recursive]
141
+
142
+ self.paranoid_value = nil
143
+ self.save
144
+ end
145
+ end
146
+ end
147
+
148
+ def recover_dependent_associations(window, options)
149
+ self.class.dependent_associations.each do |association|
150
+ if association.collection? && self.send(association.name).paranoid?
151
+ self.send(association.name).unscoped do
152
+ self.send(association.name).paranoid_deleted_around_time(paranoid_value, window).each do |object|
153
+ object.recover(options) if object.respond_to?(:recover)
154
+ end
155
+ end
156
+ elsif association.macro == :has_one && association.klass.paranoid?
157
+ association.klass.unscoped do
158
+ object = association.klass.paranoid_deleted_around_time(paranoid_value, window).send('find_by_'+association.foreign_key, self.id)
159
+ object.recover(options) if object && object.respond_to?(:recover)
160
+ end
161
+ elsif association.klass.paranoid?
162
+ association.klass.unscoped do
163
+ id = self.send(association.foreign_key)
164
+ object = association.klass.paranoid_deleted_around_time(paranoid_value, window).find_by_id(id)
165
+ object.recover(options) if object && object.respond_to?(:recover)
166
+ end
167
+ end
168
+ end
169
+ end
170
+
171
+ def act_on_dependent_destroy_associations
172
+ self.class.dependent_associations.each do |association|
173
+ if association.collection? && self.send(association.name).paranoid?
174
+ association.klass.with_deleted.instance_eval("find_all_by_#{association.foreign_key}(#{self.id.to_json})").each do |object|
175
+ object.destroy!
176
+ end
177
+ end
178
+ end
179
+ end
180
+
181
+ def deleted?
182
+ !paranoid_value.nil?
183
+ end
184
+ alias_method :destroyed?, :deleted?
185
+
186
+ private
187
+ def paranoid_value=(value)
188
+ self.send("#{self.class.paranoid_column}=", value)
189
+ end
190
+
191
+ end
192
+
193
+ end
194
+
195
+ # Extend ActiveRecord's functionality
196
+ ActiveRecord::Base.send :extend, ActsAsParanoid
197
+
198
+ # Push the recover callback onto the activerecord callback list
199
+ ActiveRecord::Callbacks::CALLBACKS.push(:before_recover, :after_recover)
@@ -0,0 +1,38 @@
1
+ require 'active_support/core_ext/array/wrap'
2
+
3
+ module ParanoidValidations
4
+ class UniquenessWithoutDeletedValidator < ActiveRecord::Validations::UniquenessValidator
5
+ def validate_each(record, attribute, value)
6
+ finder_class = find_finder_class_for(record)
7
+
8
+ if value && record.class.serialized_attributes.key?(attribute.to_s)
9
+ value = YAML.dump value
10
+ end
11
+
12
+ sql, params = mount_sql_and_params(finder_class, record.class.quoted_table_name, attribute, value)
13
+
14
+ # This is the only changed line from the base class version - it does finder_class.unscoped
15
+ relation = finder_class.where(sql, *params)
16
+
17
+ Array.wrap(options[:scope]).each do |scope_item|
18
+ scope_value = record.send(scope_item)
19
+ relation = relation.where(scope_item => scope_value)
20
+ end
21
+
22
+ if record.persisted?
23
+ # TODO : This should be in Arel
24
+ relation = relation.where("#{record.class.quoted_table_name}.#{record.class.primary_key} <> ?", record.send(:id))
25
+ end
26
+
27
+ if relation.exists?
28
+ record.errors.add(attribute, :taken, options.except(:case_sensitive, :scope).merge(:value => value))
29
+ end
30
+ end
31
+ end
32
+
33
+ module ClassMethods
34
+ def validates_uniqueness_of_without_deleted(*attr_names)
35
+ validates_with UniquenessWithoutDeletedValidator, _merge_attributes(attr_names)
36
+ end
37
+ end
38
+ end
metadata ADDED
@@ -0,0 +1,87 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: cure_rails3_acts_as_paranoid
3
+ version: !ruby/object:Gem::Version
4
+ hash: 25
5
+ prerelease:
6
+ segments:
7
+ - 0
8
+ - 1
9
+ - 1
10
+ version: 0.1.1
11
+ platform: ruby
12
+ authors:
13
+ - Goncalo Silva
14
+ autorequire:
15
+ bindir: bin
16
+ cert_chain: []
17
+
18
+ date: 2012-02-27 00:00:00 -05:00
19
+ default_executable:
20
+ dependencies:
21
+ - !ruby/object:Gem::Dependency
22
+ name: activerecord
23
+ prerelease: false
24
+ requirement: &id001 !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ~>
28
+ - !ruby/object:Gem::Version
29
+ hash: 5
30
+ segments:
31
+ - 3
32
+ - 1
33
+ version: "3.1"
34
+ type: :runtime
35
+ version_requirements: *id001
36
+ description: Active Record (>=3.1) plugin which allows you to hide and restore records without actually deleting them. Check its GitHub page for more in-depth information.
37
+ email:
38
+ - goncalossilva@gmail.com
39
+ executables: []
40
+
41
+ extensions: []
42
+
43
+ extra_rdoc_files: []
44
+
45
+ files:
46
+ - lib/rails3_acts_as_paranoid.rb
47
+ - lib/validations/uniqueness_without_deleted.rb
48
+ - LICENSE
49
+ - README.markdown
50
+ has_rdoc: true
51
+ homepage: http://github.com/goncalossilva/rails3_acts_as_paranoid
52
+ licenses: []
53
+
54
+ post_install_message:
55
+ rdoc_options: []
56
+
57
+ require_paths:
58
+ - lib
59
+ required_ruby_version: !ruby/object:Gem::Requirement
60
+ none: false
61
+ requirements:
62
+ - - ">="
63
+ - !ruby/object:Gem::Version
64
+ hash: 3
65
+ segments:
66
+ - 0
67
+ version: "0"
68
+ required_rubygems_version: !ruby/object:Gem::Requirement
69
+ none: false
70
+ requirements:
71
+ - - ">="
72
+ - !ruby/object:Gem::Version
73
+ hash: 23
74
+ segments:
75
+ - 1
76
+ - 3
77
+ - 6
78
+ version: 1.3.6
79
+ requirements: []
80
+
81
+ rubyforge_project: cure_rails3_acts_as_paranoid
82
+ rubygems_version: 1.5.2
83
+ signing_key:
84
+ specification_version: 3
85
+ summary: Active Record (>=3.1) plugin which allows you to hide and restore records without actually deleting them.
86
+ test_files: []
87
+