Last active
December 9, 2015 22:28
-
-
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.
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
# 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 |
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
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); | |
} | |
}); |
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
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