我有2-3个“表单”模型,我正在验证密码的格式是否正确等等。
如何重构我的代码,以便在代码库中不重复这个逻辑3次?
class ResetPasswordForm
include ActiveModel::Model
attr_accessor :password, :password_confirmation
validates_presence_of :password, presence: true,
length: { minimum: 8, maximum: 20},
confirmation: true
#validates_length_of :password, :minimum => 8, :maximum => 64, :allow_blank => false
validate :password_complexity
def password_complexity
unless password.blank?
errors.add(:password, "must contain a upper case character") unless password.match(/[A-Z]/)
end
end
end
答案 0 :(得分:1)
如果您使用的是Rails5,您会注意到您的模型现在继承自ApplicationRecord,然后继承自ActiveRecord :: Base。因此,如果在Rails5上,您可以将您的方法添加到ApplicationRecord,然后在模型中的before_action中引用它。如果在Rails< = 4上,您可以在lib文件夹中创建一个新模块:lib/password_complexity.rb
。
module PasswordComplexity
def check_the_password
password_present?
password_complexity
end
def password_complexity
unless self.password.blank?
errors.add(:password, "must contain a upper case character") unless password.match(/[A-Z]/)
end
end
def password_present?
if self.password.blank? || self.password.length < 8 || self.password.length > 20 || self.password != self.password_confirmation
errors.add(:password, "some message")
end #Youll want to change this probably to multiple if's that have specific error messages.
end
end
然后在模型中添加以下行:include PasswordComplexity
并添加:
validate :check_the_password
到你的模特。
注意:遵循我在引用PasswordComplexity时所做的命名约定很重要,Rails将搜索文件password_complexity.rb