Alex. b Alex. b - 5 months ago 25
Ruby Question

Rails: optimizing a method

I have the following method that checks user birthdate (in "%d/%m/%Y" format) to be at least 18.

def person_age
if person_birthdate.present?
now = Time.now.utc.to_date
begin
parsedDate = Date.parse(person_birthdate, '%d/%m/%Y')

diff = now.year - parsedDate.year
diff -= (diff.years.since(parsedDate) > now ? 1 : 0)

if diff < 18
errors.add :person_birthdate, 'You should be at least 18'
end
rescue
errors.add :person_birthdate, 'Date not valid'
end
else
errors.add :person_birthdate, 'Date not valid'
end
end


But too many if conditions, any idea how to make it look better?

Answer

You should use built-in and custom validations.

validates :person_birthdate, presence: true
validate  :check_age, if: -> { person_birthdate.present? }

private

def check_age
  date = Date.parse(person_birthdate, '%d/%m/%Y')
  unless d > 18.years.ago
    errors.add(:person_birthdate, 'message here')
  end
end

if: -> { person_birthdate.present? } allows to call custom validation only when the condition is true.