Skip to content

Instantly share code, notes, and snippets.

@ahoward
Created March 14, 2014 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahoward/9552602 to your computer and use it in GitHub Desktop.
Save ahoward/9552602 to your computer and use it in GitHub Desktop.
class Trash
include Mongoid::Document
field(:type => String)
field(:data => Hash)
index(:type => 1)
def Trash.destroy(document)
create(
:type => document.class.name,
:data => document.as_document
)
end
def Trash.destroy!(document)
destroy(document)
ensure
document.destroy
end
def undestroy
model = eval(type)
if model.respond_to?(:undestroy)
model.undestroy(data)
else
doc = model.new
data.each do |attr, value|
doc.write_attribute(attr, value)
end
if doc.save
destroy
doc
else
false
end
end
end
def Trash.undestroy_all(&block)
results = []
all.each do |trash|
result = trash.undestroy
block ? block.call(result) : results.push(result)
end
block ? nil : results
end
def Trash.empty!
destroy_all
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment