之間不必要的重複,我有責任屬性驗證兩類:減少兩班
class NameValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
message = options.fetch(:message, I18n.t('errors.attributes.name.invalid'))
record.errors[attribute] << message unless NameValidator.valid_name?(value)
end
def self.valid_name?(name)
name =~ /\A[a-z][\w\p{Blank}]+\z/i
end
end
,第二個
class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
message = options.fetch(:message, I18n.t('errors.attributes.email.invalid'))
record.errors[attribute] << message unless EmailValidator.valid_email?(value)
end
def self.valid_email?(email)
email =~ /\[email protected]+\..+\z/i
end
end
,他們基本上是相同的。我應該使用受保護的實用方法從一個類繼承它們嗎?
恕我直言,這將是一個很好的問題http://codereview.stackexchange.com/ –