Skip to content

Instantly share code, notes, and snippets.

@jean-francois-labbe
Forked from dhh/comments_channel.rb
Created December 16, 2020 14:24
Show Gist options
  • Save jean-francois-labbe/75a8b4345324508197e7f73ff4ec6022 to your computer and use it in GitHub Desktop.
Save jean-francois-labbe/75a8b4345324508197e7f73ff4ec6022 to your computer and use it in GitHub Desktop.
On-boarding a specialized broadcast method in the channel itself
# Channel
class CommentsChannel < ApplicationCable::Channel
def self.broadcast_comment(comment)
broadcast_to comment.message, comment: CommentsController.render(
partial: 'comments/comment', locals: { comment: comment }
)
end
def follow(data)
stop_all_streams
stream_for current_user.account.messages.find(data['message_id'])
rescue ActiveRecord::RecordNotFound
reject
end
def unfollow
stop_all_streams
end
end
# Comment
class Comment < ApplicationRecord
belongs_to :message
after_create_commit -> { CommentsChannel.broadcast_comment(self) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment