Skip to content

Instantly share code, notes, and snippets.

@gdiggs
Created October 8, 2016 15:51
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 gdiggs/ce923af76ac06cbf9ba5ff0d14983abe to your computer and use it in GitHub Desktop.
Save gdiggs/ce923af76ac06cbf9ba5ff0d14983abe to your computer and use it in GitHub Desktop.
Generalized Soft Deletion for Rails
class Example < ActiveRecord::Base
include SoftDeletion
end
module SoftDeletion
def self.included(base)
base.class_eval do
default_scope { where(deleted: false) }
end
end
def destroy
update_attribute(:deleted, true)
end
end
require "spec_helper"
describe SoftDeletion do
class Fun < ActiveRecord::Base
include SoftDeletion
end
around :each do |example|
connection = ActiveRecord::Base.connection
connection.create_table :funs do |t|
t.boolean :deleted, default: "f"
end
example.run
connection.drop_table :funs
end
it "soft-deletes objects" do
fun = Fun.create!
fun.destroy
expect(Fun.unscoped.where(id: fun.id)).to be_present
end
it "defaults the scope" do
fun1 = Fun.create!
fun2 = Fun.create!
fun2.destroy
expect(Fun.count).to eq(1)
expect(Fun.unscoped.count).to eq(2)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment