lib/sn_foil/contexts/destroy_context.rb in snfoil-0.3.0 vs lib/sn_foil/contexts/destroy_context.rb in snfoil-0.4.0
- old
+ new
@@ -4,26 +4,33 @@
require_relative './setup_context'
require_relative './change_context'
module SnFoil
module Contexts
- module DestroyContext
+ module DestroyContext # rubocop:disable Metrics/ModuleLength
extend ActiveSupport::Concern
included do
include SetupContext
include ChangeContext
end
class_methods do
- attr_reader :i_before_destroy_hooks, :i_after_destroy_hooks, :i_after_destroy_success_hooks, :i_after_destroy_failure_hooks
+ attr_reader :i_setup_destroy_hooks, :i_before_destroy_hooks, :i_after_destroy_hooks,
+ :i_after_destroy_success_hooks, :i_after_destroy_failure_hooks
def destroy(id:, user: nil, **options)
new(user).destroy(**options, id: id)
end
+ def setup_destroy(method = nil, **options, &block)
+ raise ArgumentError, '#setup_destroy requires either a method name or a block' if method.nil? && block.nil?
+
+ (@i_setup_destroy_hooks ||= []) << { method: method, block: block, if: options[:if], unless: options[:unless] }
+ end
+
def before_destroy(method = nil, **options, &block)
- raise ArgumentError, '#on_destroy requires either a method name or a block' if method.nil? && block.nil?
+ raise ArgumentError, '#before_destroy requires either a method name or a block' if method.nil? && block.nil?
(@i_before_destroy_hooks ||= []) << { method: method, block: block, if: options[:if], unless: options[:unless] }
end
def after_destroy(method = nil, **options, &block)
@@ -51,11 +58,11 @@
options.merge! object: wrap_object(object || scope.resolve.find(id))
end
def destroy(**options)
options[:action] = :destroy
- options = setup_destroy(setup_change(**options))
+ options = before_setup_destroy_object(**options)
options = setup_destroy_object(**options)
authorize(options[:object], :destroy?, **options)
options = destroy_hooks(**options)
unwrap_object(options[:object])
end
@@ -78,10 +85,14 @@
def after_destroy_failure(**options)
options
end
+ def setup_destroy_hooks
+ self.class.i_setup_destroy_hooks || []
+ end
+
def before_destroy_hooks
self.class.i_before_destroy_hooks || []
end
def after_destroy_hooks
@@ -95,9 +106,18 @@
def after_destroy_failure_hooks
self.class.i_after_destroy_failure_hooks || []
end
private
+
+ def before_setup_destroy_object(**options)
+ options = setup_destroy(**options)
+ options = setup_destroy_hooks.reduce(options) { |opts, hook| run_hook(hook, opts) }
+ options = setup_change(**options)
+ options = setup_change_hooks.reduce(options) { |opts, hook| run_hook(hook, opts) }
+ options = setup(**options)
+ setup_hooks.reduce(options) { |opts, hook| run_hook(hook, opts) }
+ end
# This method is private to help protect the order of execution of hooks
def destroy_hooks(options)
options = before_destroy_save(options)
options = if options[:object].destroy