title: Rails 4 Live Streaming
body: <p>I am following this railscast that it explains how to implement a chat application. I have followed everything step by step, and it seems to be working until the point I started using redis for the publish/subscribe version of it to make it faster, but my application is not updating the chats now. I have to refresh the page each time a new message comes in!</p>
  
  <p>Here is my code:</p>
  
  <pre><code>class MessagesController &lt; ApplicationController
      include ActionController::Live
  
    def index
      @messages = Message.all
    end
  
    def create
      response.headers["Content-Type"] = "text/javascript"
      @message = Message.create!(params[:message].permit(:content, :name))
      $redis.publish('messages.create',@message.to_json)
    end
  
    def events   
      response.headers["Content-Type"] = "text/event-stream"
      redis=Redis.new
      redis.psubscribe('messages.create') do |on|
        on.pmessage do |pattern, event, data|
         response.stream.write("event: #{event}\n")
        end
      end
      rescue IOError
        logger.info "Stream closed"
      ensure
        redis.quit
        response.stream.close  
      end
  end
  </code></pre>
  
  <p>in messages/index.html.erb</p>
  
  <pre><code>&lt;h1&gt;Chat&lt;/h1&gt;
  
  &lt;ul id="chat"&gt;
    &lt;%= render @messages %&gt;
  &lt;/ul&gt;
  
  &lt;%= form_for Message.new, remote: true do |f| %&gt;
    &lt;%= f.text_field :name, placeholder: "Name" %&gt;
    &lt;%= f.text_field :content %&gt;
    &lt;%= f.submit "Send" %&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>I have a .js file in the assets/javascript folder which takes care of the listening to server events.</p>
  
  <pre><code>var evnt = new EventSource('/messages/events');
  
  evnt.addEventListener('messages.create', function(e){
    var message;
    message = $.parseJSON(e.data).message;
    return $('#chat').append($('&lt;li&gt;').text("" + message.name + ": " + message.content));
  });
  </code></pre>
  
  <p>I am starting the redis-server on a separate terminal like this</p>
  
  <pre><code>$: redis-server
  </code></pre>
  
  <p>I did not install redis using brew, just downloaded a tar file and untarred it. It is recognized by the system so it should be ok.</p>
  
  <p>When I try the application it does not update the chats with the new messages. I need to refresh the page to make them show. Anyhelp?</p>