Reputation: 11107
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.
Upvotes: 0
Views: 168
Reputation: 52357
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.
Upvotes: 1