Rails rescue_from - response with flash message only (redirect_to)
Hi!
I want to implement a rescue from internal server error. The problem is not the rescue itself, but how to respond to Wiselinks only a Rails flash message without loading a partial or template.
Following an example. First include the file in application controller:
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
include Concerns::ExceptionHandler
...
end
Here the included file:
# app/controllers/concerns/exception_handler.rb
module Concerns
module ExceptionHandler
extend ActiveSupport::Concern
included do
rescue_from ActionController::RoutingError, with: :render_404
end
def render_404
message = 'Sorry, action can not be done!'
if request.wiselinks?
redirect_to request.referer_with_wiselinks, alert: message # flash don't work
else
redirect_to :back, alert: message
end
end
end
The alert message is not shown. The problem is, that redirect_to finishes with status 302 and the browser redirects to the new path (in this case request.referer_with_wiselinks) where the flash is already "depleted".
Any idea how i can solve this problem?
I have try out a code where the flash messages are added in the response headers (after_filter). This works fine but on Wiselinks redirect_to this flash messages headers should be bypassed to the next request and response in case of redirect_to!
Problem
The unfortunate truth about AJAX and the 302 redirect is that jQuery ajax can't get the headers from the return because the browser never gives them to the XHR. When a browser sees a 302 it automatically applies the redirect.
flash.keep don't solves the problem. See http://api.rubyonrails.org/classes/ActionDispatch/Flash/FlashHash.html#method-i-keep
Solved the problem! In a before_filter in the application controller I have found flash.discard! Removing flash.discard all works fine!
To handle headers in Wiselinks callbacks (javascript events) I have added xhr in callbacks for page:fail, page:redirected, page:done. The xhr in the callbacks can be very useful. @igor-alexandrov can you please merge this changes?
Example
$(document).off('page:done').on('page:done', function(event, $target, status, url, data, xhr) {
message = xhr.getResponseHeader('X-Flash-Message');
type = xhr.getResponseHeader('X-Flash-Message-Type');
});
Javascript Events
- page:done ($target, status, url, data, xhr)
- page:fail ($target, status, url, error, code, xhr)
- page:redirected ($target, render, url, xhr)
See my commits: https://github.com/phlegx/wiselinks/commits/master