I've got a naive implementation of flash messages working in satisfyingly few lines of code.
Here's the
unit test.
At the moment the flash cookie gets cleared in the response if all of these conditions are met:
- The response is 2xx
- InternalRequestMarker says the request wasn't internal
- The media type is text/html or application/xhtml+xml
I'm not so sure about the last condition, but ClearFlashPredicate is at least pluggable so you can override it or decorate it yourself.
Does anyone see any problem with these rules? Rails makes you explicitly state that you want to hold on to the flash over a redirect. I wanted to avoid that complexity. You can always implement your own version if you need different logic- it's only 4 classes.
Is there a better way to do it? I was considering triggering deletion of values in Flash by explicitly consuming them, but didn't want to over-complicate it.
Flash is a Model internally, so you can customise to your heart's content. An obvious extension is to have an "includes" value and using that to include more complex messages in your decorator so I didn't have to make sure messages and errors are added as lists.
I'm not happy with Flash class at the moment. Suggestions for clean up are gratefully received. In other, familiar news: I wish StringTemplate let you iterate over single values.
At the moment, I'm doing this in my default decorator:
$include.("/messages").body;format="raw"$
<html>
<head>
<title>Flash Messages</title>
<meta name="decorator" content="none"/>
</head>
<body>
<div>
$messages:{message |
<div class="alert alert-success">$message$</div>
}$
$errors:{error |
<div class="alert alert-error">$error$</div>
}$
</div>
</body>
</html>