title: Ruby on Rails: Observe model changes from controller action
body: <p>I want to emit server-sent events whenever the <code>update</code> action in a controller is called (or whenever my model is updated). I currently have a working <code>watch</code> action in the same controller with a dummy emitter:</p>
  
  <pre><code>def watch
      self.response.headers["Content-Type"] = "text/event-stream"
      self.response.headers["Last-Modified"] = Time.now.ctime.to_json
      self.response_body = Enumerator.new do |y|
          100.times do |i|
              sleep 5
              y &lt;&lt; ["event: message", "data: #{i}\n\n"].join("\n")
          end
      end
      # TODO catch IO error when client disconnects
  end
  </code></pre>
  
  <p><strong>How can I get an enumerable object that yields/returns a value when <code>update</code> is called?</strong> (NB: It doesn't truly have to be an Enumerable; but it does have to respond to <code>#each</code> for this streaming technique to work.) In some senses, I'm trying to implement an event-driven architecture in Rails I guess.</p>
  
  <p>I'm aware of <a href="http://www.ruby-doc.org/stdlib-1.9.3/libdoc/observer/rdoc/Observable.html" rel="nofollow">Observable</a> but I can't figure out how to get my observer to be enumerable as required for this... or how to put an observer in the Enumerator (as above) without having a loop and sleep timer.</p>
  
  <p>The purpose of this is to have changes that are made to the database sent to all other users currently logged in, such that each user always has a current reflection of the database.</p>
  
  <p>Thanks-</p>