vendredi 1 juillet 2016

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?

Aucun commentaire:

Enregistrer un commentaire