给rails的ActiveModel::Errors类扩展了两个方法:insert、keep

作者在 2022-12-02 23:39:00 发布以下内容
用例见注释:
#coding: utf-8

class ActiveModel::Errors

  # add的简写方法
  # u.errors.append :code, '邮件验证码不正确'
  def append(*l)
    self.add l[0], :custom, message: l[1]
  end

  # 从开头插入,跟append相反
  # u.errors.insert :code, '邮件验证码不正确'
  def insert(*l)
    errors = [[l[0], :custom, message: l[1]]]
    self.each do |e|
      errors.append([e.attribute, e.type, message: e.message])
    end

    self.clear
    errors.each do |e|
      self.add *e
    end
    return self
  end

  # u.errors.keep(:email)
  # u.errors.keep(:username, :email)
  # u.errors.keep(:username, :email => [:blank, :invalid])  # 此为下面一行的简写
  # u.errors.keep(:username, :email => { in: [:blank, :invalid] })
  # u.errors.keep(:username, :email => { not: [:taken] })
  def keep(*args)
    errors = []
    args.each do |arg|
      if arg.is_a? Hash
        label = arg.keys.first
        condition = arg.values.first
        if condition.is_a? Array
          key = :in
          values = condition
        else
          key = condition.keys.first
          values = condition.values.first
        end
        if key == :in
          errors += self.where(label).select{ |e| e.type.in? values }
        elsif key == :not
          errors += self.where(label).reject{ |e| e.type.in? values }
        end
      else
        errors += self.where(arg)
      end
    end

    clone = self.dup
    clone.clear
    errors.each do |e|
      clone.add e.attribute, e.type, message: e.message
    end
    return clone
  end

end
Ruby | 阅读 1341 次
文章评论,共0条
游客请输入验证码
浏览2888493次
文章归档
最新评论
  • 静夜思:-1是多核
  • 时光拾荒者:CtrlCV还是强的😝
  • 硬识岩丝:解决了,太感谢了~