Rails5.2 나왔습니다. 이 타이밍에 Action Cable을 사용해 보도록 하겠습니다.

15127 단어 ActionCableRails
안녕하세요!Rails5.2 나왔네!
그러니 이번에는 액션 케이블을 시도해 보자.
...ActiveStorage라고 생각하는 사람은 m()에게 떳떳하지 못하다m
뒤돌아보면 개인적으로 액션 케이블이 사용한 설치를 해본 적이 없거나, 원래는 필요 없이 접촉하지 않은 분들도 많을 텐데(직감) 이 타이밍에 액션 케이블을 꼭 접촉해야 합니다!

만든 물건


이번에 만든 것은 간단한 채팅 앱이다!
인상은 이렇습니다.

여러 개의 브라우저를 시작하고 한 브라우저에 투고하면 다른 브라우저에 실시간으로 반영할 수 있는 것을 만들고 싶습니다.
이 기사를 쓸 때.
https://qiita.com/jnchito/items/aec75fab42804287d71b
여기를 참고했어요.(통속적이고 알기 쉽게 정리하여 순조롭게 시도했다.)

어쨌든 가져오기


아무튼 rails new죠!
$ rails new action_cable_sample --skip-turbolinks -d postgresql
터보링크스가 방해가 되는 아이가 될 것 같으니 퇴장을 부탁합니다.
rails new 종료 후rails db:create도 준비해야 한다.
채팅에 필요한 컨트롤러와 모델을 미리 만듭니다.
$ rails g controller chat_rooms show
$ rails g model chat_message content:text
$ rails db:migrate
대체로 명령을 실행하여 배우들을 모두 집합시키다.
제작된 컨트롤러와view를 정리합니다.
app/controllers/chat_rooms_controller.rb
class ChatRoomsController < ApplicationController
  def show
    @chat_messages = ChatMessage.all
  end
end
app/views/chat_rooms/show.html.erb
<div id="chat">
  <% @chat_messages.each do |chat_message| %>
    <p><%= chat_message.content %></p>
  <% end %>
</div>
이번엔 시도니까 대화방을 방문하는 코스면 날아갈 수 있어.
config/routes.rb
Rails.application.routes.draw do
  root 'chat_rooms#show'
end

채널 만들기


이제 웹 소켓 통신에 필요한 Action Cable 파일을 만듭니다.
말은 그렇지만 하는 일도 간단한 지령 집행일 뿐이야!
$ rails g channel chat_room speak
다음 두 개의 파일을 생성합니다.
app/channels/chat_room_channel.rb
class ChatRoomChannel < ApplicationCable::Channel
  def subscribed
    # stream_from "some_channel"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

  def speak
  end
end
app/assets/javascripts/channels/chat_room_channel.js

App.chat_room = App.cable.subscriptions.create("ChatRoomChannel", {
  connected: function() {
    // Called when the subscription is ready for use on the server
  },

  disconnected: function() {
    // Called when the subscription has been terminated by the server
  },

  received: function(data) {
    // Called when there's incoming data on the websocket for this channel
  },

  speak: function() {
    return this.perform('speak');
  }
});
그런 다음 Action Cable에서 사용할 라우트를 준비합니다.
config/routes.rb
mount ActionCable.server => '/cable' # 追記
여기까지 Action Cable을 사용할 준비가 완료되었습니다!

먼저 동작을 확인합니다.


Action Cable에 연결되었는지 확인합니다.
액세스rails s를 시작합니다http://localhost:3000.
방문 후 cherome 검증 도구를 열고 실행해 보십시오 App.chat_room.speak().
app/assets/javascripts/channels/chat_room_channel.jsApp.chat_room Action Cable에 대입된 대상App.chat_room.speak()!
그러고 보니 코드적인 건 아직 전혀 안 썼지만 액티브 케이블에 연결해서 이렇게 완성됐어요!

우선 실시간으로 alert를 올려보도록 하겠습니다.


먼저 App.chat_room.speak('Hello') 과 컨트롤러를 사용한 후, alert를 시작하는 브라우저에 줍니다.
우선 app/channels/chat_room_channel.rb를 다음과 같이 수정하겠습니다.
subscribed에서 어떤 채널을 구독할지 지정합니다. (이번에는 chat_room_channelspeak에 구독 채널에 메시지를 보내는 것을 기록했습니다.
app/channels/chat_room_channel.rb
class ChatRoomChannel < ApplicationCable::Channel
  def subscribed
    stream_from 'chat_room_channel'
  end

  # 変更ないので省略

  def speak(data)
    ActionCable.server.broadcast 'chat_room_channel', message: data['message']
  end
end
변경되면 아래app/assets/javascripts/channels/chat_room.js는 다음과 같이 수정됩니다.
app/assets/javascripts/channels/chat_room.js
App.chat_room = App.cable.subscriptions.create("ChatRoomChannel", {
  // 変更ないので省略

  // 購読側が受け取る内容
  received: function(data) {
    alert(data['message']);
  },

  // App.chat_room.speak(message)で配信する
  speak: function(message) {
    return this.perform('speak', { message: message });
  }
});
speak에 매개 변수를 추가합니다.
추가된 매개 변수를perform에 전송합니다.
receiveld는 구독 채널에서 보내는 경우 어떻게 해야 하는지를 기록합니다.
이번에alert주고 싶어서alert(data['message'])썼어요.
전송된 정보는 데이터 대상을 타고 입장합니다!
메시지는 ActionCable.server.broadcast 'chat_room_channel', message: data['message']message: data['message']에서 지정됩니다.
여기까지 하면 콘솔에서 실행App.chat_room.speak('Hello')하면alert에서 Hello가 표시된 것을 확인할 수 있습니다.

수다 떨듯이.


여기서부터 채팅 바람!
우선 투고app/views/chat_rooms/show.html.erb까지 하기 위해 말미에 다음과 같은 내용을 보충한다.
app/views/chat_rooms/show.html.erb
<form>
  投稿: <input type="text" />
  <input type="submit" value="投稿" onClick="postChatMessage()" />
</form>
투고 버튼을 누르면 이 함수에 먼저 불을 붙인다postChatMessage().postChatMessage()는 이렇게 설치되어 있습니다.
먼저 app/assets/javascripts/application.js의 말미에도 기입해 주세요.
app/assets/javascripts/application.js
function postChatMessage() {
  event.preventDefault();
  var element = document.querySelector('input[type="text"]');
  App.chat_room.speak(element.value);
  element.value = '';
}
투고 버튼을 누르면 지금까지 콘솔에서 진행된 것App.chat_room.speak을 실행한다.
채널의speak에 DB에 추가 등록하는 처리
단순히 캐치크레이트 처리!
app/channels/chat_room_channel.rb
def speak(data)
  chat_message = ChatMessage.create!(content: data['message']) # 追記
  ActionCable.server.broadcast 'chat_room_channel', message: chat_message.content
end
가능하다면, 채팅이 투고된 후에 화면에 반영될 수 있도록 Received에 DOM 처리를 적어 주십시오.
alert를 취소하고 다음 기술로 변경합니다.
app/assets/javascripts/channels/chat_room.js
received: function(data) {
  var chat = document.getElementById('chat');
  var newMessage = document.createElement('p');
  newMessage.innerText = data['message'];
  chat.appendChild(newMessage);
},
편지를 받은 후id="chat"DOM에 투고 내용의 p라벨이 추가되었습니다!
이렇게 되면 처음에 본 수다 따위가 움직인다!

최후


Action Cable에 손댄 적이 없어서 신선해요!
ActionCable은 Rails뿐만 아니라 JS도 연관이 있어서 헷갈리기 쉬운 기능인 것 같은데...
다음에도 ActiveStorage를 잘 건드리도록 하겠습니다.

좋은 웹페이지 즐겨찾기