Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
after invited_user introduced
InviteRedeemer = Struct.new(:invite) do
def redeem
result = invited_user
Invite.transaction do
if mark_invite_redeemed == 1
# Create the user if we are redeeming the invite and the user doesn't exist
result = create_user_if_missing
# If there are topic invites for private topics
allow_access_to_private_topics
# Check for other invites by the same email. Don't redeem them, but approve their
# topics.
approve_topic_invitations
send_welcome_message
# Notify the invitee
notify_invitee
end
end
result
end
#private
def invited_user
@invited_user ||= get_existing_user
end
def mark_invite_redeemed
# Avoid a race condition
# Return true if 1 row was updated
Invite.update_all('redeemed_at = CURRENT_TIMESTAMP',
['id = ? AND redeemed_at IS NULL AND created_at >= ?',
invite.id,
SiteSetting.invite_expiry_days.days.ago])
end
def create_user_if_missing
result = invited_user
result ||= User.create_for_email(invite.email, trust_level: SiteSetting.default_invitee_trust_level)
result.send_welcome_message = false
result
end
def get_existing_user
User.where(email: invite.email).first
end
def allow_access_to_private_topics
invite.topics.private_messages.each do |t|
t.topic_allowed_users.create(user_id: invited_user.id)
end
end
def approve_topic_invitations
Invite.where('invites.email = ? and invites.id != ?', invite.email, invite.id).includes(:topics).where(topics: {archetype: Archetype::private_message}).each do |i|
i.topics.each do |t|
t.topic_allowed_users.create(user_id: invited_user.id)
end
end
end
def send_welcome_message(result)
if Invite.update_all(['user_id = ?', result.id], ['email = ?', invite.email]) == 1
result.send_welcome_message = true
end
end
def notify_invitee
invite.invited_by.notifications.create(notification_type: Notification.types[:invitee_accepted],
data: {display_username: invited_user.username}.to_json)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment