Skip to content

Commit

Permalink
get undestroy working
Browse files Browse the repository at this point in the history
git-svn-id: http://llama/svn/trunk/ruby/acts_as_soft_deletable@220 bb26965d-a405-0410-8ce8-d62df5cd24e9
  • Loading branch information
(no author) committed Mar 4, 2008
1 parent 42758de commit b5e36bb
Show file tree
Hide file tree
Showing 3 changed files with 274 additions and 4 deletions.
20 changes: 16 additions & 4 deletions lib/acts_as_soft_deletable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,17 @@ def acts_as_soft_deletable
self.set_table_name "deleted_#{model_class.table_name}"

extend Deleted::ClassMethods
include Deleted::InstanceMethods
end
end
end

module Deleted

module ClassMethods
def create_table(create_table_options = {})
connection.create_table(table_name, create_table_options) do |t|
model_class.columns.select{|c| !excluded_columns.include?(c.name)}.each do |col|
model_class.columns.select{|c| c.name != model_class.primary_key}.each do |col|
t.column col.name, col.type
#:limit => col.limit,
#:default => col.default,
Expand All @@ -37,10 +39,20 @@ def create_table(create_table_options = {})
t.datetime :deleted_at
end
end
end

# returns a list of column names that will not be archived
def excluded_columns
[model_class.primary_key]
module InstanceMethods
# restore the model from deleted status. Will destroy the deleted record and recreate the original record
def undestroy!
self.class.transaction do
model = self.class.model_class.new
self.attributes.reject{|k,v| k == 'deleted_at'}.keys.each do |key|
model.send("#{key}=", self.send(key))
end
model.save!
self.destroy
end
true
end
end
end
Expand Down
4 changes: 4 additions & 0 deletions test/base_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,9 @@ def test_destroy_creates_a_deleted_model

deleted = Artist::Deleted.find_by_name('Chick Corea')
assert_equal artist.attributes, deleted.attributes.reject{|k,v| k == 'deleted_at'}

assert deleted.undestroy!
assert_equal artist.attributes, Artist.find_by_name('Chick Corea').attributes
assert_nil Artist::Deleted.find_by_name('Chick Corea')
end
end
Loading

0 comments on commit b5e36bb

Please sign in to comment.