Created
May 18, 2023 12:46
-
-
Save goulvench/40c7666c8b70e1f56461ba62b8747bff to your computer and use it in GitHub Desktop.
Force Rails to render flash messages for XHR responses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# To display flash messages inside XHR responses, | |
# place this file in app/controllers/concerns/ | |
# then include it in ApplicationController | |
module RenderFlashNowForXhr | |
extend ActiveSupport::Concern | |
private | |
# Flash messages are not directly available for XHR requests | |
# This concern rewrites `render notice: message` to `flash.now.notice = message; render` | |
def render(*args) | |
if request.xhr? && args.length.positive? | |
options = args.find { |arg| arg.is_a? Hash } | |
return super if options.nil? | |
[:alert, :error, :notice, :success].each do |type| | |
flash.now[type] = options[type] if type.in? options | |
end | |
end | |
super | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing!