Agile Web Development with Rails, Edition 5

12.1 Iteration H1: Capturing an Order 11.4 Iteration F4: Hide an Empty Cart

11.5 Iteration F5: Broadcasting Updates

create a channel

rails generate channel products
      create  app/channels/products_channel.rb
   identical  app/assets/javascripts/cable.js
      create  app/assets/javascripts/channels/

create a channel

edit app/channels/products_channel.rb
class ProductsChannel < ApplicationCable::Channel
  def subscribed
    stream_from "products"
  def unsubscribed
    # Any cleanup needed when channel is unsubscribed

Update price when notified of price changes

edit app/assets/javascripts/channels/
App.products = App.cable.subscriptions.create "ProductsChannel",
  connected: ->
    # Called when the subscription is ready for use on the server
  disconnected: ->
    # Called when the subscription has been terminated by the server
  received: (data) ->
    document.getElementsByTagName("main")[0].innerHTML = data.html

send updates when price changes

edit app/controllers/products_controller.rb
  def update
    respond_to do |format|
      if @product.update(product_params)
        format.html { redirect_to @product,
          notice: 'Product was successfully updated.' }
        format.json { render :show, status: :ok, location: @product }
        @products = Product.all
        ActionCable.server.broadcast 'products',
          html: render_to_string('store/index', layout: false)
        format.html { render :edit }
        format.json { render json: @product.errors,
          status: :unprocessable_entity }

Run tests

rails test
Run options: --seed 1099
# Running:
Finished in 0.829654s, 37.3650 runs/s, 80.7566 assertions/s.
31 runs, 67 assertions, 0 failures, 0 errors, 0 skips

Save our progress

git commit -a -m "AJAX"
[master 6e378ba] AJAX
 3 files changed, 26 insertions(+), 7 deletions(-)
git tag iteration-f

12.1 Iteration H1: Capturing an Order 11.4 Iteration F4: Hide an Empty Cart