2019-10-16 06:52:30 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2019-08-14 09:48:44 +00:00
|
|
|
class AccountBuilder
|
|
|
|
include CustomExceptions::Account
|
2019-12-24 12:02:27 +00:00
|
|
|
pattr_initialize [:account_name!, :email!]
|
2019-08-14 09:48:44 +00:00
|
|
|
|
|
|
|
def perform
|
2019-10-20 08:47:26 +00:00
|
|
|
validate_email
|
|
|
|
validate_user
|
|
|
|
ActiveRecord::Base.transaction do
|
|
|
|
@account = create_account
|
|
|
|
@user = create_and_link_user
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
2019-10-20 08:47:26 +00:00
|
|
|
rescue StandardError => e
|
|
|
|
@account&.destroy
|
|
|
|
puts e.inspect
|
|
|
|
raise e
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def validate_email
|
|
|
|
address = ValidEmail2::Address.new(@email)
|
2019-10-20 08:47:26 +00:00
|
|
|
if address.valid? # && !address.disposable?
|
2019-08-14 09:48:44 +00:00
|
|
|
true
|
|
|
|
else
|
2019-10-20 08:47:26 +00:00
|
|
|
raise InvalidEmail.new(valid: address.valid?) # , disposable: address.disposable?})
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def validate_user
|
|
|
|
if User.exists?(email: @email)
|
2019-10-20 08:47:26 +00:00
|
|
|
raise UserExists.new(email: @email)
|
2019-08-14 09:48:44 +00:00
|
|
|
else
|
|
|
|
true
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def create_account
|
|
|
|
@account = Account.create!(name: @account_name)
|
|
|
|
end
|
|
|
|
|
|
|
|
def create_and_link_user
|
|
|
|
password = Time.now.to_i
|
2019-10-20 08:47:26 +00:00
|
|
|
@user = @account.users.new(email: @email,
|
|
|
|
password: password,
|
|
|
|
password_confirmation: password,
|
|
|
|
role: User.roles['administrator'],
|
|
|
|
name: email_to_name(@email))
|
2019-08-14 09:48:44 +00:00
|
|
|
if @user.save!
|
|
|
|
@user
|
|
|
|
else
|
2019-10-20 08:47:26 +00:00
|
|
|
raise UserErrors.new(errors: @user.errors)
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def email_to_name(email)
|
|
|
|
name = email[/[^@]+/]
|
2019-10-20 08:47:26 +00:00
|
|
|
name.split('.').map(&:capitalize).join(' ')
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
|
|
|
end
|