From c10f9311678ff2183443bc03e153b30d3b68ff74 Mon Sep 17 00:00:00 2001 From: Azul Date: Tue, 20 May 2014 13:09:59 +0200 Subject: Controller#flash_for instead of FlashResponder FlashResponder added a flash before responding. However at the point of responding objects have already been saved. So there is no way to test if they were changed. Now instead we can call flash_for resource before resource.save and it will add the flash messages only if the resource was actually changed. --- app/controllers/controller_extension/flash.rb | 33 +++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 app/controllers/controller_extension/flash.rb (limited to 'app/controllers/controller_extension') diff --git a/app/controllers/controller_extension/flash.rb b/app/controllers/controller_extension/flash.rb new file mode 100644 index 0000000..6a62351 --- /dev/null +++ b/app/controllers/controller_extension/flash.rb @@ -0,0 +1,33 @@ +module ControllerExtension::Flash + extend ActiveSupport::Concern + + protected + + def flash_for(resource, options = {}) + return unless resource.changed? + message = flash_message_for(resource) + type = flash_type(resource) + if message.present? + flash[type] = [message, flash[type]].join(' ') + end + end + + def flash_message_for(resource) + I18n.t flash_i18n_key(resource), + scope: :flash, + cascade: true, + resource: resource.class.model_name.human + end + + def flash_i18n_key(resource) + namespace = [action_name] + namespace += controller_path.split('/') + namespace << flash_type(resource) + namespace.join(".") + end + + def flash_type(resource) + resource.valid? ? :success : :error + end + +end -- cgit v1.2.3