Created
March 15, 2017 21:11
-
-
Save carolineartz/8808a65638935fb6dda11fa18f67996f to your computer and use it in GitHub Desktop.
cancellable
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 Direct | |
# Models that include this mixin must | |
# - have a `cancelled_at` column | |
# - implement paranoia with `deleted_at` column | |
# To use this mixin, include the module and call the macro | |
# The macro takes options hash that will be forwarded on, | |
# to an after_destroy callback. Typically passing a conditional | |
# `if` or `unless` would be appropriate. | |
# | |
# | |
# module Direct | |
# class Flight < ActiveRecord::Base | |
# include Cancellable | |
# | |
# cancellable if: :approved_start_date? | |
# end | |
# end | |
module Cancellation | |
extend ActiveSupport::Concern | |
included do | |
default_scope { where(cancelled_at: nil) } | |
validates :deleted_at, absence: true, if: :cancelled_at | |
after_destroy :cancel!, after_destroy_args | |
scope :with_cancelled, -> { unscope(where: :cancelled_at) } | |
scope :only_cancelled, -> { with_cancelled.where.not(cancelled_at: nil) } | |
end | |
end | |
module Cancellable | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def cancellable(args = {}) | |
cattr_accessor :after_destroy_args | |
self.after_destroy_args = args | |
include Cancellation | |
include InstanceMethods | |
end | |
end | |
module InstanceMethods | |
def cancel! | |
update_columns( | |
cancelled_at: deleted_at, | |
deleted_at: nil | |
) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment