Skip to content

Instantly share code, notes, and snippets.

@liroyleshed
Forked from dhh/comments_channel.rb
Created September 26, 2020 17:33
Show Gist options
  • Save liroyleshed/697f90cf1ef00a8e119a722761df70f8 to your computer and use it in GitHub Desktop.
Save liroyleshed/697f90cf1ef00a8e119a722761df70f8 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