Created
July 2, 2020 14:23
-
-
Save glennfu/26d00d349f99a508deb611360ca57d9b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ArticleChannel < ApplicationCable::Channel | |
def subscribed | |
@article = Article.find(params[:article_id]) | |
@editor_id = params[:editor_id] | |
# Write it only if the editor is truly nil in a single query to avoid race conditions | |
Article.where(id: @article.id, editor: nil).update(editor: @editor_id) | |
stream_for @article | |
# Send this even if we're not the editor. If we are the editor, it'll confirm it | |
# If we're not the editor, it'll let us know that too | |
NotifyArticleUpdateJob.perform_later(@article) | |
end | |
def unsubscribed | |
Rails.logger.debug "ActionCable unsubscribe" | |
user_has_left | |
end | |
def unsubscribe_from_channel | |
Rails.logger.debug "ActionCable unsubscribe_from_channel" | |
user_has_left | |
end | |
private | |
def user_has_left | |
stop_all_streams | |
if @editor_id && @article | |
reloaded = Article.find_by(id: @article.id) | |
# Dumping the DB at the end of a spec can blow up here | |
return if reloaded.nil? && Rails.env.test? | |
if reloaded.editor == @editor_id | |
@article.update(editor: nil) | |
NotifyArticleUpdateJob.perform_later(@article) | |
end | |
end | |
@article = nil | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment