Standardise flash messages across your app

19 July 2007 An addition to ActionController::Base gives me a new method called "message_for" that takes an object and a message type (that for some reason I elected to name 'error' as its local variable).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
module ActionController
  class Base
    
    # This custom extension allows us to call message_for(object, :error_sym) and return a set of
    # standard messages - this means all of our error messages are standardised
    # across the various places that make use of the flash div.
    # It is mixed into ActionController:Base such that we can call it from any controller.
    def message_for(object, error)
      case error
      when :ar_not_found
        flash[:error] = object + " " + DEFAULT_MESSAGES[:ar_not_found]
      when :ar_invalid
        flash[:error] = DEFAULT_MESSAGES[:ar_invalid]
      when :created
        flash[:notice] = object + " " + DEFAULT_MESSAGES[:created]
      when :updated
        flash[:notice] = object + " " + DEFAULT_MESSAGES[:updated]
      when :destroyed_succ
        flash[:notice] = object + " " + DEFAULT_MESSAGES[:destroyed_succ]
      when :destroyed_fail
        flash[:error] = object + " " + DEFAULT_MESSAGES[:destroyed_fail]
      end
    end
    
  end
end


The DEFAULT_MESSAGES constant is something I setup in environment.rb by loading a YAML file into a constant - this YAML file is where I go to change the default messages across the entire app. I also set the specific type of flash that I want to appear, you'll notice that the not found error produces a flash[:error] whereas the updated action produces a flash[:notice] - this helps me to ensure that every type of action has a consistent appearance in the flash whenever it is triggered.


DEFAULT_MESSAGES = YAML.load(File.open(File.join("#{RAILS_ROOT}", "lib", "messages.yml"))).symbolize_keys!


The messages.yml file just includes lines that map strings straight onto the keys used in the message_for method, e.g.:
ar_not_found: record with that ID does not exist
ar_invalid: Some fields were invalid, please review and try again

Now with a bit of TextMate magic, I map the key combination "rarmf" to produce this block of text (and other combinations depending on the specific error I want to throw)
1
2
3
  rescue ActiveRecord::RecordNotFound
    message_for("Order", :ar_not_found)
    redirect_to(admin_orders_path)


Now if I want to change the message that appears when a record cannot be found, I just change it in messages.yml and it changes across the entire app when I reload the webserver (DEFAULT_MESSAGES is defined as a constant).

Comments

Sorry, comments are closed for this article.