Class: Decidim::Comments::VoteComment

Inherits:
Rectify::Command
  • Object
show all
Defined in:
app/commands/decidim/comments/vote_comment.rb

Overview

A command with all the business logic to upvote a comment

Instance Method Summary collapse

Constructor Details

#initialize(comment, author, options = { weight: 1 }) ⇒ VoteComment

Public: Initializes the command.

comment - A comment author - A user options - An optional hash of options (default: { weight: 1 })

* weight: The vote's weight. Valid values 1 and -1.


13
14
15
16
17
# File 'app/commands/decidim/comments/vote_comment.rb', line 13

def initialize(comment, author, options = { weight: 1 })
  @comment = comment
  @author = author
  @weight = options[:weight]
end

Instance Method Details

#callObject

Executes the command. Broadcasts these events:

  • :ok when everything is valid.

  • :invalid if the vote wasn’t create

Returns nothing.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'app/commands/decidim/comments/vote_comment.rb', line 25

def call
  case @weight
  when 1
    previous_vote = @comment.up_votes.find_by(author: @author)
    if previous_vote
      previous_vote.destroy!
    else
      @vote = @comment.up_votes.create!(author: @author)
    end
  when -1
    previous_vote = @comment.down_votes.find_by(author: @author)
    if previous_vote
      previous_vote.destroy!
    else
      @vote = @comment.down_votes.create!(author: @author)
    end
  else
    return broadcast(:invalid)
  end

  notify_comment_author if @vote
  broadcast(:ok, @comment)
rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique
  broadcast(:invalid)
end

#notify_comment_authorObject



51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'app/commands/decidim/comments/vote_comment.rb', line 51

def notify_comment_author
  Decidim::EventsManager.publish(
    event: "decidim.events.comments.comment_#{upvote? ? "upvoted" : "downvoted"}",
    event_class: upvote? ? Decidim::Comments::CommentUpvotedEvent : Decidim::Comments::CommentDownvotedEvent,
    resource: @comment.commentable,
    affected_users: [@comment.author],
    extra: {
      comment_id: @comment.id,
      weight: @weight,
      downvotes: @comment.down_votes.count,
      upvotes: @comment.up_votes.count
    }
  )
end