Adding flash message as render argument

Currently you can add a flash notice to your render call like so:

flash[:notice] = “Notice me!”

render :index

Similar to how it can be passed with redirect_to, I’d like to be able to pass it as an argument to render:

render :index, notice: “Notice me!”

I’ve been using a monkey patch to allow this, but if you think this is a valid feature, I’d love to write a pull request. Here’s the code for the patch, I can’t find where I got it, but I wasn’t the original author:

https://github.com/tomprats/tomify/blob/master/config/initializers/flash_patch.rb

Thanks,

Tom

To prevent top-level variable congestion, this may be better:

render :index, flash: {notice: ‘hi’}

Sean - I’d agree with that but I think it’d be good to have it consistent with redirect_to.

The key purpose of the flash is to provide a variable that survives a redirect. I get that there may well be special circumstances that require setting the flash in the same request as the response is being sent from, but that’s a pretty uncommon use case (or at least should be). So I think it’s actually better that this is called out on a separate line, since it’s somewhat abnormal. If the render call had it backed in, there’d be an implicit endorsement that using the flash in this manner is standard operating procedure.

But if your app does have this as a standard pattern, then all good with freedom patch! :smiley:

Thanks for you response. That makes a lot of sense. In this case I was using flash for notifications, which sometimes would need to be passed immediately, and sometimes held onto for the next request. In this case I think I’ll stick with the freedom patch, but if flash and my notification functionality diverge in the future, I’ll know why. Thanks for you help!

In case if you want to display flash message immediately on render you can use flash.now to set the message:

flash.now[:notice] = ‘Show me without redirect’

``

Very easy!