Rails:优化方法

时间:2016-07-01 07:54:06

标签: ruby-on-rails ruby date if-statement logic

我有以下方法检查用户生日(以“%d /%m /%Y”格式)至少为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

但如果条件太多,任何想法如何让它看起来更好?

3 个答案:

答案 0 :(得分:2)

您应该使用内置和自定义验证。

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? }只允许在条件为true时调用自定义验证。

答案 1 :(得分:1)

我认为你想要的是:

validates_presence_of :person_birthdate # which will generate the "Date is required message"

等等:

def person_age
  date = Date.parse(person_birthdate, '%d/%m/%Y')
  unless d > 18.years.ago
    errors.add :person_birthdate, "You should be at least 18."    
  end
end

答案 2 :(得分:0)

Rails在某些方面很好,但是这里所有这些validate[s]都是一种矫枉过正的行为:

def person_age
  case Date.today - Date.parse(
         person_birthdate, '%d/%m/%Y'
       ).advance(years: 18) rescue nil
  when NilClass
    errors.add :person_birthdate, 'Date not valid'
  when -Float::INFINITY..0
    errors.add :person_birthdate, 'You should be at least 18'
  else puts "Allowed!"
  end
end