jason328 jason328 - 7 months ago 77
Ruby Question

Selecting the first flash message in Rails

I only want to grab the first flash message. I have to send this message to an object. So far I have

flash.first.last if flash.present? and flash.first.present?

In some cases the flash doesn't exist at all so I have to first check that it exists, then see if it has a message. I honestly don't like it. Does the FlashHash or Rails have a method that does this behavior out-of-the-box? Is there a cleaner way to do this? Thanks.


If you're looking for a way to shorten it, you can use safe navigation:

flash.try(:first).try(:last) # Ruby < 2.3
flash&.first&.last           # Ruby >= 2.3

For list of flash hash methods refer to ActionDispatch::Flash::FlashHash documentation.