Created
October 8, 2016 15:51
-
-
Save gdiggs/ce923af76ac06cbf9ba5ff0d14983abe to your computer and use it in GitHub Desktop.
Generalized Soft Deletion for Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Example < ActiveRecord::Base | |
include SoftDeletion | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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