jhawthorn/discard

A breakdown of Discard, the gem that does soft-deletion right

Most apps don’t actually destroy data when a record is “deleted”, instead they soft-delete the data by setting a flag in the database and excluding it from future queries. This week we are taking a look at the popular soft-deletion gem discard by jhawthorn. What I love about this gem is that unlike the other it does not add a default scope to your models to exclude the discarded records. This week is a bit of a short one, let’s get to it.

Documentation

While the gem is very lightweight the documentation is still very extensive. It shows you how to install, use, and customize the integration of the gem. It goes further to show you how you can use the various callbacks provided by the gem such as after_discard and other things like working with associations.

Simply a Concern

The cool thing about this gem is just how lightweight it is. It is essentially a Rails concern packaged as a gem. All of the functionality exists in the Model module. Which is the class that you include in your models that you want to be soft-deleted.

Methods

I love when code is simple to understand and reason about and one of the best ways to ensure that is the case is to have small, well named methods. This concern has a handful of methods that it adds to your models and they all are named so that what they do is obvious.

They follow the Rails convention of having bang (!) and non-bang versions of the methods. For example, there is discard_all and discard_all! where the bang version raises an exception if something goes wrong.

Another thing that you will notice in the screenshot above is that they re-use existing methods, keeping the code DRY.

Callbacks

The gem is a good example of defining and utilizing custom callbacks. It uses define_custom_callbacks to define a callback for discard and undiscard.

Custom callback definition

Then the callbacks are executed during the corresponding operation as seen below:

TL;DR

The discard gem is a Rails concern distributed as a Rails gem. It is a great, small library that does one thing very well. Should you find yourself looking to handle soft-deletions in your app it is a great library to reach for. It is also a great example to use if you simply want to create the concern in your application without adding another gem.

Until next time!