Skip to content

Instantly share code, notes, and snippets.

@carolineartz
Created March 15, 2017 21:11
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 carolineartz/8808a65638935fb6dda11fa18f67996f to your computer and use it in GitHub Desktop.
Save carolineartz/8808a65638935fb6dda11fa18f67996f to your computer and use it in GitHub Desktop.
cancellable
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