【问题标题】:What is the difference between `stream_from` and `stream_for` in ActionCable?ActionCable 中的 `stream_from` 和 `stream_for` 有什么区别?
【发布时间】:2016-12-24 10:29:33
【问题描述】:

here 的描述似乎暗示 stream_for 仅在传入记录时使用,但总体而言,文档相当模糊。谁能解释stream_fromstream_for 之间的区别以及为什么要使用一个而不是另一个?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-5 actioncable


    【解决方案1】:

    stream_for 只是stream_from 的简单包装方法。

    当您需要与特定模型相关的流时,stream_for 会自动为您从模型和频道生成广播。

    假设您有一个 chat_room 类的 ChatRoom 实例,

    stream_from "chat_rooms:#{chat_room.to_gid_param}"
    

    stream_for chat_room # equivalent with stream_from "chat_rooms:Z2lkOi8vVGVzdEFwcC9Qb3N0LzE"
    

    这两行代码做同样的事情。

    https://github.com/rails/rails/blob/master/actioncable/lib/action_cable/channel/streams.rb

    【讨论】:

    • to_gid_param 部分的意义何在?你不能直接说chat_room_#{params[:chat_room_id]} 吗?
    • 它只是用于将任意字符串编码为有效的非空白字符串吗?还是背后有什么别的想法?
    • stream_for is used when there is a particular record (or record and association) we want updates about. Under the hood, Action Cable is generating a unique string for that record or that record and its association and then calls the stream_for [sic -- probably should be 'stream_from'] method.Source: sitepoint.com/action-cable-and-websockets-an-in-depth-tutorial
    • gid_param 很难预测。它阻止了提供随机 id 来获取流的攻击者。
    • @the_critic 你如何从客户端订阅一个你事先不知道的频道?我的意思是你如何订阅它?
    【解决方案2】:

    kevinhyunilkim's answer 几乎没问题,但前缀取决于通道名称,而不是模型类。

    class CommentsChannel < ApplicationCable::Channel
      def subscribed
        stream_for article
        # is equivalent to
        stream_from "#{self.channel_name}:{article.to_gid_param}"
        # in this class this means
        stream_from "comments:{article.to_gid_param}"
      end
    
      private
    
      # any activerecord instance has 'to_gid_param'
      def article
        Article.find_by(id: params[:article_id])
      end
    end
    

    您也可以将简单的字符串传递给stream_for,它只是添加频道名称。

    【讨论】:

      【解决方案3】:

      stream_for 将对象作为参数

      class UserChannel < ApplicationCable::Channel
        def subscribed
          stream_for current_user
        end
      end
      

      stream_from 将字符串作为参数

      class ChatChannel < ApplicationCable::Channel
        def subscribed
          stream_from "chat_channel_#{params[:id]}"
        end
      end
      

      查看article,我认为它很好地处理了这个概念

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-02
        • 2011-12-12
        • 2010-09-16
        • 2012-03-14
        • 2012-02-06
        • 2011-02-25
        • 2011-11-22
        • 2015-03-26
        相关资源
        最近更新 更多