Skip to content

Instantly share code, notes, and snippets.

@gusrub
Created March 4, 2018 03:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gusrub/bf648ce54fca579c2c766b795dc6eebf to your computer and use it in GitHub Desktop.
Save gusrub/bf648ce54fca579c2c766b795dc6eebf to your computer and use it in GitHub Desktop.
User Service
# service name hints that it does
class CreateUserService
# default attributes that all services should have
attr_reader :errors, :messages, :output
# custom attributes for what this service does
attr_reader :user, :send_email
# we receive all parameters in the initialization
def initialize(user:, send_email: true)
@user = user
@send_email = send_email
end
def perform
reinitialize
@user.token = TokenProvider.generate(@user.email) unless @user.token.present?
if @user.valid?
@user.save
UserMailer.welcome_message(user).deliver if @send_email
@messages << "User #{user.email} successfully created"
@output = @user
else
@errors << @user.errors.full_messages
end
@errors.empty?
end
private
# this just makes sure that each time perform is called the errors and
# messages are reinitialized
def reinitialize
@errors = []
@messages = []
@output = nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment