Files
grecia/app/models/verification/management/email.rb
Javi Martín 7ca55c44e0 Apply Rails/SaveBang rubocop rule
Having exceptions is better than having silent bugs.

There are a few methods I've kept the same way they were.

The `RelatedContentScore#score_with_opposite` method is a bit peculiar:
it creates scores for both itself and the opposite related content,
which means the opposite related content will try to create the same
scores as well.

We've already got a test to check `Budget::Ballot#add_investment` when
creating a line fails ("Edge case voting a non-elegible investment").

Finally, the method `User#send_oauth_confirmation_instructions` doesn't
update the record when the email address isn't already present, leading
to the test "Try to register with the email of an already existing user,
when an unconfirmed email was provided by oauth" fo fail if we raise an
exception for an invalid user. That's because updating a user's email
doesn't update the database automatically, but instead a confirmation
email is sent.

There are also a few false positives for classes which don't have bang
methods (like the GraphQL classes) or destroying attachments.

For these reasons, I'm adding the rule with a "Refactor" severity,
meaning it's a rule we can break if necessary.
2019-10-23 14:39:31 +02:00

68 lines
1.9 KiB
Ruby

class Verification::Management::Email
include ActiveModel::Model
attr_accessor :document_type
attr_accessor :document_number
attr_accessor :email
validates :document_type, :document_number, :email, presence: true
validates :email, format: { with: Devise.email_regexp }, allow_blank: true
validate :validate_user
validate :validate_document_number
delegate :username, to: :user, allow_nil: true
def user
@user ||= User.where(email: email).first
end
def user?
user.present?
end
def save
return false unless valid?
plain_token, encrypted_token = Devise.token_generator.generate(User, :email_verification_token)
user.update!(document_type: document_type,
document_number: document_number,
residence_verified_at: Time.current,
level_two_verified_at: Time.current,
email_verification_token: plain_token)
Mailer.email_verification(user, email, encrypted_token, document_type, document_number).deliver_later
true
end
def save!
validate! && save
end
private
def validate_user
return if errors.count > 0
if !user?
errors.add(:email, I18n.t("errors.messages.user_not_found"))
elsif user.level_three_verified?
errors.add(:email, I18n.t("management.email_verifications.already_verified"))
end
end
def validate_document_number
return if errors.count > 0
if document_number_mismatch?
errors.add(:email,
I18n.t("management.email_verifications.document_mismatch",
document_type: ApplicationController.helpers.humanize_document_type(user.document_type),
document_number: user.document_number))
end
end
def document_number_mismatch?
user? && user.document_number.present? &&
(user.document_number != document_number || user.document_type != document_type)
end
end