たれみみマンデー

【Rails5】ActionCableチャットコード

汚いのはお許しを・・・以下ソースだけ。

app/assets/javascripts/channels/product.coffee

jQuery(document).on 'turbolinks:load', ->

open_messages = $('#open_messages')

if $('#open_messages').length > 0
  if (!App.product)
   App.product = App.cable.subscriptions.create { channel: "ProductChannel",product_id: 
   open_messages.data('product_id')},
   connected: ->


   disconnected: ->

   received: (data) ->

   $('#open_messages').append '<div>' + data['open_message'] + '</div>'


   open_chat: (open_message) ->
   @perform 'open_chat', {open_message: open_message} #, seller_name: current_seller.name


  $(document).on 'click', '.comment_button', (event) ->

   text = $('[data-behavior~=open_chat_input]').val()

 if (text != "")
   App.product.open_chat text
   $('[data-behavior~=open_chat_input]').val("")
   event.preventDefault()

app/channels/product_channel.rb

class ProductChannel < ApplicationCable::Channel
  def subscribed
    stream_from "product_channel_#{params['product_id']}"
  end

  def unsubscribed

  end

  def open_chat(data)
    OpenMessage.create!(product_id: params['product_id'],sent_user: current_user.id,content: 
data['open_message'])
    OrderMailer.open_chat(params['product_id'],current_user.id).deliver_now
   # ActionCable.server.broadcast 'product_channel',{content: data['open_message']}
  end
end

 
 

app/jobs/***broadcast_job.rb

class OpenMessageBroadcastJob < ApplicationJob
  queue_as :default

  def perform(open_message)
    ActionCable.server.broadcast "product_channel_#{open_message.product_id}", {open_message: 
    render_message(open_message)}
  end

private
 def render_message(open_message)
   ApplicationController.renderer.render(partial: 'open_messages/open_message', locals: { open_message: open_message })
  end
end


app/views/**.rb

<% if signed_in? %>
  <input type="hidden" name="current_user_name" value="<%= current_devise_user.id %>" 
class="current_user_name">
<% end %>
<div id="open_messages", data-product_id="<%= @product.id %>">
  <%= render partial: @open_messages %>
</div>

<form>
  <label>コメント投稿:
    <% if signed_in? %> 
      <%= button_tag type: 'button', class: "comment_button" do %>
        <i class="fa fa-paper-plane" aria-hidden="true"></i>
      <% end %>
    <% end %>
    <input type="text" data-behavior="open_chat_input" class="open_chat"></>
  </label>
</form>