Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MaherSaif/bd93df31acaca518ee6a500ce056e366 to your computer and use it in GitHub Desktop.
Save MaherSaif/bd93df31acaca518ee6a500ce056e366 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment