Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Intermediate refactoring of InviteRedeemer
InviteRedeemer = Struct.new(:invite) do
def redeem
result = nil
Invite.transaction do
# Avoid a race condition
row_count = Invite.update_all('redeemed_at = CURRENT_TIMESTAMP',
['id = ? AND redeemed_at IS NULL AND created_at >= ?', invite.id, SiteSetting.invite_expiry_days.days.ago])
if row_count == 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(result)
# Check for other invites by the same email. Don't redeem them, but approve their
# topics.
approve_topic_invitations(result)
send_welcome_message(result)
# Notify the invitee
notify_invitee(result)
else
# Otherwise return the existing user
result = get_existing_user
end
end
result
end
private
def create_user_if_missing
result = get_existing_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(result)
invite.topics.private_messages.each do |t|
t.topic_allowed_users.create(user_id: result.id)
end
end
def approve_topic_invitations(result)
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: result.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(result)
invite.invited_by.notifications.create(notification_type: Notification.types[:invitee_accepted],
data: {display_username: result.username}.to_json)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment