ActionController :: Live - Rails中的SSE

时间:2015-01-26 19:24:54

标签: ruby-on-rails multithreading concurrency server-sent-events puma

我希望数据库中的更改能够在没有服务器重新加载的情况下反映在页面上。

控制器

class ProductController < ApplicationController
  include ActionController::Live

  def index
    @product = Product.available
    response.headers['Content-Type'] = 'text/event-stream'
    sse = SSE.new(response.stream)
    sse.write @product
  ensure
    sse.close
  end
end 

查看

<p><%= @product[:price] %></p>

我正在使用Puma。

当我更新数据库中的产品时,更改不会反映在网页上。

我错过了什么?

1 个答案:

答案 0 :(得分:2)

Rails无法实时更新视图。它提供了html,然后它可以通过一些JavaScript来监听流并处理事件。

我创造了一个宝石,淋浴,为你处理所有这些。 https://github.com/kpheasey/shower

使用Shower,解决方案就是这样。

首先,您需要发布更新事件,这可以通过产品模型上的after_update回调来完成。

class Product < ActiveRecord::Base
    after_update :publish_event

    def publish_event
        Shower::Stream.publish('product.update', self)
    end
end

然后你需要一些javascript来监听事件流并对其采取行动。

$ ->
    stream = new Shower('/stream', ['product.update'])

    stream.addEventListener('product.update', (event) ->
      product = JSON.parse(event.data)
      $('p').html(product.price)
    )