Skip to content

Instantly share code, notes, and snippets.

@sanjayginde
Last active December 9, 2015 22:28
Show Gist options
  • Save sanjayginde/4337351 to your computer and use it in GitHub Desktop.
Save sanjayginde/4337351 to your computer and use it in GitHub Desktop.
Example of using the flash hash in Rails, with AJAX and a global jQuery listener.
# Add Flash messages to response
#
# Reference: http://stackoverflow.com/a/10167659/224139
# Location: app/controllers/concerns
module Concerns::AjaxFlashable
extend ActiveSupport::Concern
included do
after_filter :flash_to_headers
end
private
def flash_to_headers
return unless request.xhr?
response.headers['X-Message'] = flash_message
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, :alert, :warning, :notice].each do |type|
return flash[type] unless flash[type].blank?
end
end
def flash_type
[:error, :alert, :warning, :notice].each do |type|
return type unless flash[type].blank?
end
end
end
jQuery(document).ajaxComplete(function (event, xhr, opts) {
var type = xhr.getResponseHeader('X-Message-Type') || 'notice';
var message = xhr.getResponseHeader('X-Message');
if (!!message) {
// *** Here is where the HTML would be written, or a call to a
// notification plugin.
console.log('FLASH: [' + type + '] ' + message);
}
});
class PostsController < ApplicationController
include Concerns::AjaxFlashable
def create
@post = Post.new(params[:post])
if @post.save
flash[:notice] = "Your post has been created!"
respond_to do |format|
format.html { redirect_to :action => :index }
format.js { head :ok }
end
else
flash[:error] = "Sorry, there was an error saving your post."
# Could append error messages here as well...
respond_to do |format|
format.html { render :new }
format.js { head :bad_request }
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment