jason328 jason328 - 1 month ago 23
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.

Answer

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.