Class: UserInvitationService

Inherits:
Object
  • Object
show all
Defined in:
app/services/user_invitation_service.rb

Overview

Responsible for associating new or existing users with an organization

Instance Method Summary collapse

Constructor Details

#initialize(user, organization) ⇒ UserInvitationService

Returns a new instance of UserInvitationService

Parameters:

  • user (User)

    the user being invited

  • organization (Organization)

    the organization the user is joining



6
7
8
9
# File 'app/services/user_invitation_service.rb', line 6

def initialize(user, organization)
  @user = user
  @organization = organization
end

Instance Method Details

#call(invitation) {|err_msg| ... } ⇒ Object

Find or create the recipient user, and create an invitation

Parameters:

Yield Parameters:

  • err_msg (String)

    describes errors that prevent inviting the user



14
15
16
17
18
19
20
21
22
23
24
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
50
51
52
53
54
# File 'app/services/user_invitation_service.rb', line 14

def call(invitation)
  dummy_password = SecureRandom.hex(20)

  create_params = {
    password: dummy_password,
    first_name: invitation.first_name,
    last_name: invitation.last_name
  }

  recipient_user = User.
                   create_with(create_params).
                   find_or_initialize_by(email: invitation.recipient_email)

  if organization.users.exists?(recipient_user.id)
    yield "#{recipient_user} is already a member of #{organization.title}"
    return
  end

  invitation.recipient_user = recipient_user
  invitation.sender_user = user
  invitation.organization = organization

  Invitation.transaction do
    delivery_method = if recipient_user.new_record?
                        recipient_user.save!
                        :new_user
                      else
                        :existing_user
                      end

    if invitation.save
      membership = organization.memberships.find_or_create_by!(user: recipient_user, role: invitation.role)
      Rails.logger.info "Created #{membership}"
      InvitationMailer.public_send(delivery_method, invitation).deliver_now
    else
      yield invitation.error_sentence
    end
  end

  invitation
end