From 95698fac37efb03ed6083550cb0d1e21d60740ab Mon Sep 17 00:00:00 2001 From: Luis Ramos Date: Mon, 6 Jul 2020 15:36:13 +0100 Subject: [PATCH] Bring responder from spree_core --- lib/spree/responder.rb | 45 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 lib/spree/responder.rb diff --git a/lib/spree/responder.rb b/lib/spree/responder.rb new file mode 100644 index 0000000000..b87d0f0daa --- /dev/null +++ b/lib/spree/responder.rb @@ -0,0 +1,45 @@ +module Spree + class Responder < ::ActionController::Responder #:nodoc: + + attr_accessor :on_success, :on_failure + + def initialize(controller, resources, options={}) + super + + class_name = controller.class.name.to_sym + action_name = options.delete(:action_name) + + if result = Spree::BaseController.spree_responders[class_name].try(:[], action_name).try(:[], self.format.to_sym) + self.on_success = handler(controller, result, :success) + self.on_failure = handler(controller, result, :failure) + end + end + + def to_html + super and return if !(on_success || on_failure) + has_errors? ? controller.instance_exec(&on_failure) : controller.instance_exec(&on_success) + end + + def to_format + super and return if !(on_success || on_failure) + has_errors? ? controller.instance_exec(&on_failure) : controller.instance_exec(&on_success) + end + + private + + def handler(controller, result, status) + return result if result.respond_to? :call + + case result + when Hash + if result[status].is_a? Symbol + controller.method(result[status]) + else + result[status] + end + when Symbol + controller.method(result) + end + end + end +end