Skip to content

Instantly share code, notes, and snippets.

@mikew
Created October 8, 2009 21:21
Show Gist options
  • Save mikew/205434 to your computer and use it in GitHub Desktop.
Save mikew/205434 to your computer and use it in GitHub Desktop.
Convenience methods for Rails' flashes with I18n support
Given
class Post < ActiveRecord::Base
def to_s; title; end
end
Then
notice :create => :post
# flash[:notice] = I18n.t :"post.create.notice", :scope => [ :flashes ], :post => @post.to_s
error :create! => :post
# flash.now[:error] = I18n.t :"post.create.error", ...
error "let's just ignore I18n completely"
# flash[:error] = "let's just ignore I18n completely"
notice "cause we're jerks", true
# flash.now[:notice] = "cause we're jerks"
There are multiple I18n keys to determine the message
a simple `notice :create => :post` would look in
:"post.create.notice"
:"create.notice"
:create
:notice
class ApplicationController < ActionController::Base
...
def notice(*args)
set_flash :notice, *args
end
def error(*args)
set_flash :error, *args
end
def set_flash(level, *args)
if args.first.is_a? String # bypass I18n completely
message = args.shift
immediate = !args.empty? # set_flash :error, "Something went wrong", (true || :now || truthy)
end
unless message
if args.first.is_a? Hash # set_flash :notice, :create => :post
i18n_key = args.first.first.first
object = args.first.first.last
if real = instance_variable_get("@#{object}")
interpolation_options = { object => real.to_s }
end
else
i18n_key = args.first # set_flash :notice, :create
end
if i18n_key.to_s.ends_with? '!' # set_flash :error, :create! => flash.now[error] = ...
immediate = true
i18n_key = i18n_key.to_s[0...-1]
end
defaults = returning [] do |a|
a << "#{object}.#{i18n_key}.#{level}"
a << "#{i18n_key}.#{level}"
a << "#{i18n_key}"
a << "#{level}"
end.collect(&:to_sym)
message = I18n.t defaults.shift, (interpolation_options || {}).update(:default => defaults, :scope => [ :flashes ])
end
immediate ? flash.now[level] = message : flash[level] = message
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment