discourse/lib/validators/max_username_length_validator.rb
Daniel Waterworth 55a1394342 DEV: pluck_first
Doing .pluck(:column).first is a very common pattern in Discourse and in
most cases, a limit cause isn't being added. Instead of adding a limit
clause to all these callsites, this commit adds two new methods to
ActiveRecord::Relation:

pluck_first, equivalent to limit(1).pluck(*columns).first

and pluck_first! which, like other finder methods, raises an exception
when no record is found
2019-10-21 12:08:20 +01:00

22 lines
530 B
Ruby

# frozen_string_literal: true
class MaxUsernameLengthValidator
def initialize(opts = {})
@opts = opts
end
def valid_value?(value)
return false if value < SiteSetting.min_username_length
@username = User.where('length(username) > ?', value).pluck_first(:username)
@username.blank?
end
def error_message
if @username.blank?
I18n.t("site_settings.errors.max_username_length_range")
else
I18n.t("site_settings.errors.max_username_length_exists", username: @username)
end
end
end