Szukaj…


Uwagi

ActionCable był dostępny dla Rails 4.x i został dołączony do Rails 5. Umożliwia łatwe korzystanie z gniazd sieciowych do komunikacji w czasie rzeczywistym między serwerem a klientem.

[Podstawowy] Po stronie serwera

# 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

[Podstawowy] Strona klienta (Coffeescript)

app / asset / 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 / asset / javascripts / application.js # zwykle generowany w ten sposób

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

app / asset / javascripts / cable.js # zwykle generowany w ten sposób

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

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

  App.cable = ActionCable.createConsumer();

}).call(this);

Uwierzytelnianie użytkownika

# 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
Licencjonowany na podstawie CC BY-SA 3.0
Nie związany z Stack Overflow