Class: Decidim::Posts::AddReactionToResource

Inherits:
Command
  • Object
show all
Defined in:
app/commands/decidim/posts/add_reaction_to_resource.rb

Overview

A command with all the business logic related with a user reacting to a resource.

Instance Method Summary collapse

Constructor Details

#initialize(resource, current_user, current_group_id = nil, reaction_type_id) ⇒ AddReactionToResource

Public: Initializes the command.

resource - An instance of Decidim::Posts::Reactionable. current_user - The current user. current_group_id- (optional) The current_grup that is reacting to the Resource. reaction_type_id - The id of the reaction type (emoji) that the user is reacting with.



13
14
15
16
17
18
# File 'app/commands/decidim/posts/add_reaction_to_resource.rb', line 13

def initialize(resource, current_user, current_group_id = nil, reaction_type_id)
  @resource = resource
  @current_user = current_user
  @current_group_id = current_group_id
  @reaction_type = ReactionType.find(reaction_type_id)
end

Instance Method Details

#callObject

Executes the command. Broadcasts these events:

  • :ok when everything is valid, together with the resource reaction.

  • :invalid if the form was not valid and we could not proceed.

Returns nothing.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'app/commands/decidim/posts/add_reaction_to_resource.rb', line 26

def call
  return broadcast(:invalid) if existing_group_reaction?

  reaction = @resource.reactions.find_by(author: @current_user)
  if reaction.present?
    if reaction.reaction_type == @reaction_type
      if delete_reaction(reaction)
        broadcast(:ok, nil)
      else
        broadcast(:invalid)
      end
    else
      if reaction.update(reaction_type: @reaction_type)
        broadcast(:ok, reaction)
      else
        broadcast(:invalid)
      end
    end
  else
    reaction = build_resource_reaction unless reaction
    if reaction.save
      notify_reactor_followers
      broadcast(:ok, reaction)
    else
      broadcast(:invalid)
    end
  end
rescue ActiveRecord::RecordNotUnique
  broadcast(:invalid)
end