수색…


비고

ActionCable 은 Rails 4.x에서 사용할 수 있었으며 Rails 5에 번들되었습니다. 서버와 클라이언트 간의 실시간 통신을 위해 웹 소켓을 쉽게 사용할 수 있습니다.

[기본] 서버 측

# app/channels/appearance_channel.rb
class NotificationsChannel < ApplicationCable::Channel
  def subscribed
    stream_from "notifications"
  end

  def unsubscribed
  end

  def notify(data)
    ActionCable.server.broadcast "notifications", { title: 'New things!', body: data }
  end
end

[기본] 클라이언트 측 (Coffeescript)

app / assets / javascripts / channels / notifications.coffee

App.notifications = App.cable.subscriptions.create "NotificationsChannel",
  connected: -> 
    # Called when the subscription is ready for use on the server
    $(document).on "change", "input", (e)=>
      @notify(e.target.value)

  disconnected: ->
    # Called when the subscription has been terminated by the server
     $(document).off "change", "input"

  received: (data) ->
    # Called when there's incoming data on the websocket for this channel
    $('body').append(data)

  notify: (data)->
    @perform('notify', data: data)

app / assets / javascripts / application.js # 일반적으로 다음과 같이 생성됩니다.

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

app / assets / javascripts / cable.js # 일반적으로 다음과 같이 생성됩니다.

//= require action_cable
//= require_self
//= require_tree ./channels

(function() {
  this.App || (this.App = {});

  App.cable = ActionCable.createConsumer();

}).call(this);

사용자 인증

# app/channels/application_cable/connection.rb
module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.id 
      # Can replace current_user.id with usernames, ids, emails etc.
    end

    protected

    def find_verified_user
      if verified_user = env['warden'].user
        verified_user
      else
        reject_unauthorized_connection
      end
    end
  end
end


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow