Created
January 27, 2011 00:01
-
-
Save unicornrainbow/797794 to your computer and use it in GitHub Desktop.
Set flash message by convention with i18n
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 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 |
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
en: | |
controllers: | |
notice: "Default notice" | |
error: "Default error" | |
example: | |
somthing: | |
notice: "Something was done to %{foo} successfully" | |
error: "There was a problem with %{foo}" |
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 ExampleController < ApplicationController | |
def something | |
# Do something | |
success = something(params[:foo]) | |
# Set flash | |
set_flash success, params | |
# Redirect | |
redirect_to example_index_url | |
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
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 |
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 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