mirror of
https://github.com/discourse/discourse.git
synced 2025-05-22 16:11:08 +08:00
refactor Topic validation
introduce a couple of custom validators fix minor discrepancies in tests copy I18n error message keys to default location clean up validation invocation move some responsibilities out of validator into class
This commit is contained in:
9
lib/validators/quality_title_validator.rb
Normal file
9
lib/validators/quality_title_validator.rb
Normal file
@ -0,0 +1,9 @@
|
||||
require 'text_sentinel'
|
||||
require 'text_cleaner'
|
||||
|
||||
class QualityTitleValidator < ActiveModel::EachValidator
|
||||
def validate_each(record, attribute, value)
|
||||
sentinel = TextSentinel.title_sentinel(value)
|
||||
record.errors.add(attribute, :is_invalid) unless sentinel.valid?
|
||||
end
|
||||
end
|
21
lib/validators/unique_among_validator.rb
Normal file
21
lib/validators/unique_among_validator.rb
Normal file
@ -0,0 +1,21 @@
|
||||
class UniqueAmongValidator < ActiveRecord::Validations::UniquenessValidator
|
||||
def validate_each(record, attribute, value)
|
||||
old_errors = record.errors[attribute].size
|
||||
|
||||
# look for any duplicates at all
|
||||
super
|
||||
|
||||
new_errors = record.errors[attribute].size - old_errors
|
||||
|
||||
# do nothing further unless there were some duplicates.
|
||||
unless new_errors == 0
|
||||
# now look only in the collection we care about.
|
||||
dupes = options[:collection].call.where("lower(#{attribute}) = ?", value.downcase)
|
||||
dupes = dupes.where("id != ?", record.id) if record.persisted?
|
||||
|
||||
# pop off the error, if it was a false positive
|
||||
record.errors[attribute].pop(new_errors) unless dupes.exists?
|
||||
end
|
||||
end
|
||||
|
||||
end
|
Reference in New Issue
Block a user