Skip to content

Instantly share code, notes, and snippets.

@pkmishra
Forked from hbrandl/RailsFlashToHeaders.md
Last active August 29, 2015 14:02
Show Gist options
  • Save pkmishra/50a1c156aa41b8cf0ffd to your computer and use it in GitHub Desktop.
Save pkmishra/50a1c156aa41b8cf0ffd to your computer and use it in GitHub Desktop.
module AjaxFlashConcern
extend ActiveSupport::Concern
included do
after_filter :flash_to_headers
end
private
def flash_to_headers
return unless request.xhr?
msg = flash_message
#replace german umlaute encoded in utf-8 to html escaped ones
msg = msg.gsub("ä","ä").gsub("ü","ü").gsub("ö","ö").gsub("Ä","Ä").gsub("Ü","Ü").gsub("Ö","Ö").gsub("ß","ß")
response.headers['X-Message'] = msg
response.headers["X-Message-Type"] = flash_type.to_s
flash.discard # don't want the flash to appear when you reload page
end
def flash_message
[:error, :warning, :notice].each do |type|
return flash[type] unless flash[type].blank?
end
# if we don't return something here, the above code will return "error, warning, notice"
return ''
end
def flash_type
#:keep will instruct the js to not update or remove the shown message.
#just write flash[:keep] = true (or any other value) in your controller code
[:error, :warning, :notice, :keep].each do |type|
return type unless flash[type].blank?
end
#don't return the array from above which would happen if we don't have an explicit return statement
#returning :empty will also allow you to easily know that no flash message was transmitted
return :empty
end
end
<!-- flash_message.js.coffee expects to find a div with this id in your html code -->
.container-fluid
.errors__container
# encoding: UTF-8
class ApplicationController < ActionController::Base
include AjaxFlashConcern
end
$(document).ajaxComplete (event, request) ->
msg = request.getResponseHeader("X-Message")
alert_type = 'alert-success'
alert_type = 'alert-error' unless request.getResponseHeader("X-Message-Type") && request.getResponseHeader("X-Message-Type").indexOf("error") is -1
unless request.getResponseHeader("X-Message-Type") && request.getResponseHeader("X-Message-Type").indexOf("keep") is 0
#add flash message if there is any text to display
message = "<div class='.errors_container'>
<div class='alert " + alert_type + "'>
<button type='button' aria-hidden='true' class='close' data-dismiss='alert'>&times;</button>
" + msg + "
</div>
</div>"
console.log(message)
$(".errors__container").replaceWith(message) if msg
#delete the flash message (if it was there before) when an ajax request returns no flash message
# $(".errors__container").replaceWith("<div class='.errors__container'></div>") unless msg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment