title: Rails flash messages: is there a good reason they work the way they do?
body: <p>The Rails 'flash' message system is very useful, but I've always found the details of its implementation make its use awkward.</p>
  
  <p>Specifically, the flash messages are cleared at the end of a response. This means that you have to work out whether they're going to be used in a direct page render or a redirect, then inform the flash system by using 'now' if it's not a redirect.</p>
  
  <p>This seems overly complex and error-prone.</p>
  
  <p>Occasionally I find myself building things that need to exhibit flash-like behaviour, and the process I use is slightly different:</p>
  
  <pre><code>class FlashlikeStore
  
    attr_accessor :session
  
    def initialize(session)
      session[:flashlike] ||= []
      self.session = session
    end
  
    def add(name, data)
      self.store &lt;&lt; { name: name, data: data }
    end
  
    def read
      session.delete(:flashlike).to_json
    end
  
    def any?
      store &amp;&amp; store.any?
    end
  
    protected
  
    def store
      session[:flashlike]
    end
  
  end
  </code></pre>
  
  <p>With a little syntactic sugar in the application helper I can easily add my name-value pairs, and the act of reading it deletes the data. (In this case I'm actually reading this in via AJAJ, but that isn't important here.)</p>
  
  <p>The upshot is that messages are only ever read once, with no need up-front to determine or guess when they're going to appear. They're read when they're needed, then they go away.</p>
  
  <p>One could argue, I suppose, that a call to an object shouldn't both read data and change state, so the 'read' method could be split into a 'read' and a 'wipe' if you wanted to be purist that way. (Although you probably wouldn't be using Rails if you were.)</p>
  
  <p>So the question is this: am I missing something? Is there a compelling reason for the way Rails flash messaging works, with its need for the 'now' method?</p>