Skip to content

Instantly share code, notes, and snippets.

@goulvench
Created May 18, 2023 12:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save goulvench/40c7666c8b70e1f56461ba62b8747bff to your computer and use it in GitHub Desktop.
Save goulvench/40c7666c8b70e1f56461ba62b8747bff to your computer and use it in GitHub Desktop.
Force Rails to render flash messages for XHR responses
# 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
@akshayKhot
Copy link

Thanks for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment