# How to Create Custom Flash Types in Rails

*Published on May 17, 2023*

---


Sometimes you want to store some data in the&nbsp;[Rails Session](/rails-sessions)&nbsp;for the next request; for example, to display an error message or notice to the user after redirecting them to another page.

You can store this message in the session using flash, and access it in the next request. The flash is cleared in the next request.

Most of the time, we want to use the flash for two reasons:&nbsp;**to show a notice to the user, or to alert them about something**. Hence, out of the box, Rails provides two accessors on the flash object, called&nbsp;`notice`&nbsp;and&nbsp;`alert`, which let you create and access the notice and alert messages in the controllers and views respectively.

```ruby
class FlashController < ApplicationController
  def show
    flash.alert = 'usage limit exceeded!'
    flash.notice = 'the post was successfully saved'
  end
end
```

It is also possible to assign a flash message when you redirect the request. Simply pass either&nbsp;`:notice`&nbsp;or&nbsp;`:alert`&nbsp;option to the&nbsp;`redirect_to`&nbsp;method and the value will be stored in the flash.

```ruby
render home_path, notice: "You have successfully signed out."
redirect_to home_path, alert: "Oops! Something went wrong."
```

Anything you store in the flash is available in the views. You can access the flash both as an object or a Hash.

```html
<%= flash.notice %>

<%= flash[:alert] %>
```

What's more, you don't even need the flash, as Rails provides the&nbsp;`notice`&nbsp;and&nbsp;`alert`&nbsp;helper methods, so you can simply do this:

```html
<%= notice %>

<%= alert %>
```

### What if you want to add a custom flash type?

If you need a different flash type than&nbsp;`notice`&nbsp;or&nbsp;`alert`, you can simply treat the&nbsp;`flash`&nbsp;object as a plain Ruby Hash and register the type as a new key-value pair with the standard Hash syntax.

The following code registers a new type called&nbsp;`warning`.

```ruby
class FlashController < ApplicationController
  def show
    flash[:warning] = 'WARNING'
  end
end
```

Then, in your views, access the warning message as a standard Hash.

```html
<%= flash[:warning] %>
```

However, there're two drawbacks to this approach.

**1\) You don't get convenient view helpers like**&nbsp;**`notice`**&nbsp;**and**&nbsp;**`alert`****.**&nbsp;You have to use the Hash accessors in your views.

**2\) You can't pass the**&nbsp;**`warning`**&nbsp;**option in your**&nbsp;**`redirect_to`**&nbsp;**helper.**&nbsp;Instead, you'll have to set the warning manually, using the Hash syntax.

```ruby
class FlashController < ApplicationController
  def show
    # not possible
    # redirect_to home_path, warning: "logged out"
  
    redirect_to root_path, flash: { warning: 'logged out' }
  end
end
```

Can we do better?

![bob.png](https://writesoftwarewell.com/media/0atoxatesugba9trg9wkloqqpa4a.png "Bob the Builder - Yes, we can!")

## A Better Solution

You can create custom flash types using the&nbsp;`add_flash_types`&nbsp;method. Any new types you create will behave like the existing&nbsp;`notice`&nbsp;and&nbsp;`alert`&nbsp;types.

First, add the custom flash type in&nbsp;`ApplicationController`, the base class of all your Rails controllers. This will create the custom flash helper methods that are available in all views.

```ruby
class ApplicationController < ActionController::Base
  add_flash_types :warning
end
```

Now you can use the&nbsp;`warning`&nbsp;type in the redirects and access the&nbsp;`warning`&nbsp;helper in the views.

```ruby
class FlashController < ApplicationController
  def show
    redirect_to root_path, warning: "Incomplete profiles"
  end
end

# in the view
<%= warning %>
```

Pretty cool.

**Note:**&nbsp;Remember that you use the&nbsp;`add_flash_types`&nbsp;in the&nbsp;`ApplicationController`, which creates helpers that you can use in views for all &nbsp;the controllers that inherit from&nbsp;`ApplicationController`.

If you add it to&nbsp;`FlashController`&nbsp;and redirect to&nbsp;`UsersController#show`, Rails won't recognize the&nbsp;`warning`&nbsp;helper in the&nbsp;`users/show.html.erb`&nbsp;view.

_(I know because I just spent half an hour debugging and scratching my head figuring out why it couldn't find my helper.)_

> Check out this article for an in-depth explanation of Rails sessions.

[Sessions in Rails: Everything You Need to Know](/rails-sessions)

## Internal Implementation

Let's open the Rails codebase and see how the&nbsp;`add_flash_types`&nbsp;method is implemented:

```ruby
# actionpack/lib/action_controller/metal/flash.rb

def add_flash_types(*types)
  types.each do |type|
    next if _flash_types.include?(type)
    
    define_method(type) do
      request.flash[type]
    end
    helper_method(type) if respond_to?(:helper_method)
    
    self._flash_types += [type]
  end
end
```

Right away, we notice that the method accepts multiple parameters (see&nbsp;`*types`). That means you can create multiple flash types in one line as follows:

```ruby
add_flash_types :warning, :info
```

Next, it loops over each type and skips the rest of the code block if it's already registered. For this, Rails checks the&nbsp;`_flash_types`&nbsp;array, which is the internal storage for the flash types.

Then it creates a new method named after the custom type using the&nbsp;[`define_method`](https://ruby-doc.org/3.2.0/Module.html#method-i-define_method)[&nbsp;](https://ruby-doc.org/3.2.0/Module.html#method-i-define_method)method in Ruby. All this method does is access the custom flash value from the&nbsp;`request.flash`&nbsp;object.

Next, the newly created method is registered as a helper method on the current controller, using the&nbsp;[`helper_method`](https://api.rubyonrails.org/classes/AbstractController/Helpers/ClassMethods.html#method-i-helper_method)&nbsp;method in Rails. This is how you can access the flash type in the views, such as&nbsp;`<%= warning %>`.

Note that we also make sure that the controller has a&nbsp;`helper_method`&nbsp;using the&nbsp;[`respond_to?`](https://ruby-doc.org/3.2.0/Object.html#method-i-respond_to-3F)&nbsp;method in Ruby. This method verifies if you can call a method on an object.

Finally, the new type is added to the internal storage, i.e. the&nbsp;`_flash_types`&nbsp;array.

And that's how Rails registers a custom flash type.

**Have you used any custom flash types it in your apps? If yes, which new flash types did you add?**&nbsp;Let me know in the comments below.

