• Stars
    star
    147
  • Rank 243,388 (Top 5 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 13 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Turnkey Flash messages for your Rails app

Unobtrusive flash messages for Rails Build Status

Buy Me a Coffee at ko-fi.com

Ever got tired of pages that can't be cached because they contain flash messages?

Ever got tired of writing custom code to handle flash messages passed in AJAX responses?

Here comes the solution.

unobtrusive_flash takes your flash messages for the backend and automagically passes them to the frontend via HTTP cookies. This works with both regular page loads, jQuery AJAX requests, and turbolinks (from v3), does not tamper with the page body and requires about 3 extra lines of code in your app - how's that for unobtrusive?

You can pass up to 4K of text into flash this way, and you don't need to worry about cookie size since they are cleared immediately upon rendering.

Tested in all major browsers, including Internet Explorer 8 and later.

Requirements

  • Rails >=3 (Latest versions of 3.2, 4.0, 4.1, 4.2, and 5 are automatically tested)
  • jQuery (Latest versions of jQuery 1, 2 and 3 are automatically tested)

Usage

  1. Add the unobtrusive_flash gem to your Gemfile.

    gem 'unobtrusive_flash', '>=3'
  2. Add the following to the controllers that generate flash messages (or better, to the ApplicationController):

    after_action :prepare_unobtrusive_flash

    Flash messages are HTML escaped in the same manner as regular Rails view code: if a message is not html_safe, it is escaped, otherwise not. This lets you use helpers such as link_to in your messages.

  3. Include require unobtrusive_flash in your application.js.

  4. Delete flash rendering code from your views, if there was any.

  5. You have three options to render flash messages on the frontend:

Option 1: For Bootstrap projects

Also require unobtrusive_flash_bootstrap in your application.js. This file contains flash message UI based on the Bootstrap alert component.

Either declare a .unobtrusive-flash-container element somewhere on the page to contain the alerts, or Unobtrusive flash will choose the first .container or .container-fluid element on the page, or fall back to the body.

If you want the flash messages to disappear automatically, set this in your Javascript:

UnobtrusiveFlash.flashOptions["timeout"] = 2000; // milliseconds

You can config the resulting mapping classes like this:

UnobtrusiveFlash.flashOptions.mapping.notice = "success";

Option 2: For non-Bootstrap projects

Also require unobtrusive_flash_ui in your application.js and require unobtrusive_flash_ui in your application.css. These files contain a no-frills flash message UI that works out of the box.

If you want the flash messages to disappear automatically, set this in your Javascript:

UnobtrusiveFlash.flashOptions["timeout"] = 2000; // milliseconds

Option 3: Roll your own

Unobtrusive Flash triggers jQuery events when flash is received. If you want to integrate it with your own UI, implement and bind a handler:

flashHandler = function(e, params) {
  alert(
    "Received flash message " + params.message + " with type " + params.type
  );
};

$(window).bind("rails:flash", flashHandler);

Using UnobtrusiveFlash with a frontend framework that doesn't use jQuery for AJAX

Call UnobtrusiveFlash.showFlashFromCookies() in your Javascript after a completed request.

Bonus: show 'flash messages' from the front-end

Both Bootstrap and non-Bootstrap versions contain a function to display flash messages:

// Shown for 5 seconds (default)
UnobtrusiveFlash.showFlashMessage("Hello World", { type: "notice" });
// Shown forever
UnobtrusiveFlash.showFlashMessage("Error", { type: "error", timeout: 0 });

Using custom flash keys

By default, Unobtrusive Flash only displays a limited set of flash types (see UnobtrusiveFlash::ControllerMixin#unobtrusive_flash_keys). This is because some libraries use flash to keep data that is not directed at the user; for example, Devise uses a boolean flash[:timedout]. If you use other keys to store messages, override unobtrusive_flash_keys in your controller:

class ApplicationController
  def unobtrusive_flash_keys
    super << :success
  end
end

Issue with certain "hosted domains"

There are certain domains that are considered "public" or "hosting" and specifically don't share cookies across subdomains. An example is herokuapp.com - a cookie set for yourapp.herokuapp.com will not be applied for myapp.herokuapp.com. This breaks the logic of unobtrusive_flash which is tuned for regular domains that could have internal subdomains.

In this case, you should explicitly specify your domain:

class ApplicationController
  def unobtrusive_flash_domain
    request.host # last resort is hardcoding the domain here
  end
end

Running tests

This plugin's test suite includes a full set of integration tests for various versions of Rails. To run them:

bundle install
appraisal install
appraisal rake spec

The same tests are ran on Travis CI against multiple versions of Ruby and jQuery.


© 2010-2016 Leonid Shevtsov and contributors, released under the MIT license

More Repositories

1

headless

Create a virtual X screen from Ruby, record videos and take screenshots.
Ruby
960
star
2

ClickableUrls_SublimeText

Underlines URLs in Sublime Text, and lets you open them with a keystroke.
Python
152
star
3

SearchInProject_SublimeText

Use ag, ack, grep and git grep directly from Sublime Text 2 and 3
Python
124
star
4

s3-browser-upload-demo

Demonstration of direct S3 upload from browser
JavaScript
85
star
5

split_tests

Utility to split test files into parallel CI containers
Go
46
star
6

git-timesheet

A script to create a timesheet from a git log
Ruby
46
star
7

liqpay

This Ruby gem implements the LiqPAY billing system API.
Ruby
34
star
8

vydumschik

A fake data generation library in Russian
Ruby
32
star
9

monkeysort

JavaScript
32
star
10

ua-cities

A structured list of Ukrainian cities
Ruby
32
star
11

send_to_omnifocus.crx

Send to OmniFocus for Google Chrome
JavaScript
25
star
12

pivotal_shell

An (unmaintained) command-line client for Pivotal Tracker
Ruby
21
star
13

railsbug

(Discontinued) A Firebug extension for Ruby on Rails debugging
JavaScript
18
star
14

vimrun-silent

A vimrun.exe that does not spawn a visible command line window
C
12
star
15

rails_db_dump

Rake task for foolproof database dumps
Ruby
11
star
16

moves_geotag

Geotag photos using tracks from Moves.app
Shell
9
star
17

gvimfullscreen_win32

Plugin to allow full screen use in gvim on Windows
C
8
star
18

launchy

This is my fork of Launchy, the open-source application launcher. It contains some Linux-specific fixes; see commit log for more info
C++
6
star
19

kalman

JavaScript
6
star
20

vkontakte-friends-parser

Parses your Vkontakte.ru friends list, finds friends of your friends, lists them ordered by number of common friends
Ruby
5
star
21

privatbank2csv

Скрипт для преобразования выписок Приват24 в CSV
Ruby
5
star
22

tleds

Keyboard lights network indicator for Linux
C
5
star
23

jenkins.php

A PHP-on-Apache error log analyzer
PHP
4
star
24

rails-templates

Rails template - the way it should be.
Ruby
4
star
25

page_visit_tracker

A simple page visit tracker for Rails
Ruby
4
star
26

cuoco

(Deprecated in favor of using Knife) Use Capistrano for server provisioning and configuration management, not only application deployment.
Ruby
3
star
27

chef-rails-helpers

A collection of definitions that I use when deploying Ruby on Rails ails apps
Ruby
3
star
28

proxytools

Some tools for working with proxies on Ruby
Ruby
3
star
29

rubygems-gui

A Sinatra-based interface for the gem command
3
star
30

math3d

A 3D math library implemented entirely in Ruby
Ruby
2
star
31

rack_my_openid

Single-user OpenID provider implemented as a Rack (Sinatra) application.
Ruby
2
star
32

opengl-in-ruby

A little OpenGL demo in Ruby that actually works
Ruby
2
star
33

dotfiles

My dotfiles
Vim Script
2
star
34

GemLinks_SublimeText

Easily navigate Rubygems used by your project
Python
2
star
35

nenka

A VPN for friends and family
Ruby
2
star
36

glamour_math

Cross-platform 3D linear algebra for C++
C++
2
star
37

wordpress-remote-installer

Download and install WordPress through a simple web interface. You only need to manually upload a single small script to the server.
PHP
2
star
38

input_hint.js

Show placeholder text when an input is empty
JavaScript
2
star
39

ambient_theme.vim

Automatically switch Vim background based on ambient light.
C++
2
star
40

transit_in_ua

Ruby
2
star
41

uni-programming

Dnipropetrovsk National University C++ course labs.
C++
2
star
42

knife-edit-encrypted-data-bag

Edit encrypted data bags with convenience. TODO: merge with chef core codebase
Ruby
2
star
43

clojure-syntax-check

A syntax checker for Clojure
Clojure
2
star
44

behaving_rodent

A collection of behavioral helpers for Capybara the browser emulator
Ruby
2
star
45

Dash_Sublime_Text_Plugin_API

Clojure
2
star
46

send_to_omnifocus_from_pivotal_tracker

Exactly what it says on the label.
JavaScript
2
star
47

SublimeLinter-contrib-clojure-syntax-check

SublimeLinter plugin for clojure-syntax-check
Python
2
star
48

ls_feedstats

A better feed statistics plugin for WordPress
PHP
1
star
49

liqpay_demo

Demo for the liqpay gem
Ruby
1
star
50

formtastic-susy

More like Susy-ed Formtastic, but that just doesn't make sense.
1
star
51

google-reader-font-settings

Deprecated since Google Reader is now extinct
JavaScript
1
star
52

glew

Ruby SWIG bindings for GLEW
1
star
53

telegold

🏆📢 A Goldmark renderer for Telegram
Go
1
star
54

takeoff

My barebone Rails application
Ruby
1
star
55

git-housekeeping

A script to check health of project folders
Ruby
1
star
56

ruby-dynamic-text-replacement

A hack toward a DTR library for use with Rails
Ruby
1
star
57

pys60stuff

Various scripts for Python on S60
1
star
58

osx-tor-starter

A script to start and configure Tor
Shell
1
star
59

tscheck-rb

Ruby
1
star
60

rtm-for-pys60

A client for Remember The Milk for Symbian S60v5 (Nokia XpressMusic 5800). Not finished and never will be.
Python
1
star
61

one-man-shortener

A personal url shortener and image store
Ruby
1
star
62

vagrant-mpich

Script to set up an MPICH cluster with Vagrant & Chef
Ruby
1
star
63

things-app-export

Script to export the local Things.app database into a JSON file
Ruby
1
star
64

cronograph

Collect, view and analyze cronjob execution logs.
Python
1
star
65

homeblocker

DNS blocking for computer dads and moms
Go
1
star
66

omnifocus-scripts

Ruby
1
star
67

luxon-date

TypeScript
1
star
68

WindowsPhoneSync_app

Python
1
star
69

mozdebug.vim

A frontend debugger plugin for Vim
Vim Script
1
star
70

habrahabr-comments-like-reddit

Habrahabr 'comments like reddit' mod
1
star