Skip to content

Instantly share code, notes, and snippets.

@unicornrainbow
Created January 27, 2011 00:01
Show Gist options
  • Save unicornrainbow/797794 to your computer and use it in GitHub Desktop.
Save unicornrainbow/797794 to your computer and use it in GitHub Desktop.
Set flash message by convention with i18n
class ApplicationController < ActionController::Base
# Sets a flash message based on locale.
def set_flash(key, options = {})
case key
when :notice, true
flash[:notice] = flash_message(:notice, options)
when :error, false
flash[:error] = flash_message(:error, options)
else
raise ArgumentError.new "Unrecognized flash key: #{key}"
end
end
def flash_message(key, options = {})
options[:scope] ||= [:controllers, params[:controller], params[:action]]
options[:default] ||= translate(key, scope: [:controllers])
translate key, options
end
end
en:
controllers:
notice: "Default notice"
error: "Default error"
example:
somthing:
notice: "Something was done to %{foo} successfully"
error: "There was a problem with %{foo}"
class ExampleController < ApplicationController
def something
# Do something
success = something(params[:foo])
# Set flash
set_flash success, params
# Redirect
redirect_to example_index_url
end
end
require 'test_helper'
class ExampleControllerTest < ActionController::TestCase
test "something" do
put :something, foo: "bar"
assert_redirected_to example_index_path
assert_flash :notice, foo: "bar"
end
end
class ActiveSupport::TestCase
# Asserts the correct flash message was set.
def assert_flash(key, options = {})
assert_equal flash[key], @controller.send(:flash_message, :notice, options)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment