Register your own flash types [Rails 4 Countdown to 2013]

Posted on

This post is part of a series of 31 Rails 4 articles being released each day in December 2012.

In Rails 3, the ability to set flash parameters :notice and :alert in a controller redirect_to call was added. Along with this change, ActionController::Base#notice and ActionController::Base#alert were added as convenience accessors, which mapped to flash[:notice] and flash[:alert] respectively.

To set a custom flash type in your controller, you would have add the key/value pair to the controller flash hash, or you could also pass a hash to the optional :flash option in redirect_to.

As of Rails 4, developers will have the ability to register their own flash types by using the new ActionController::Flash.add_flash_types macro style method.

The Rails 3 Way

Here is an example of setting a custom error flash type in Rails 3:

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def create
    ...
    flash[:error] = "An error message for the user"
    redirect_to home_path
  end
end

# app/views/home/index
<%= flash[:error] %>

The Rails 4 Way

Here is the same example as above, using Rails 4:

# app/controllers/application_controller.rb
class ApplicationController
    ...
  add_flash_types :error, :another_custom_type
end

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def create
    ...
    redirect_to home_path,
      error: "An error message for the user"
  end
end

# app/views/home/index
<%= error %>

Further Reading

002

This post is by Kevin Faustino. Kevin is the Chief Craftsman of Remarkable Labs and also the founder of the Toronto Ruby Brigade.


Comments

comments powered by Disqus