Class: RegexReservedValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/rere_validator.rb

Constant Summary collapse

DEFAULT_MESSAGE =
{
  :invalid_characters => "can't contain invalid characters",
  :invalid_characters_at_begin => "can't begin with '.', '-', '_'",
  :invalid_characters_at_end => "can't end with '.', '-', '_'",
  :reserved_words => "can't be used a reserved words"
}.freeze

Instance Method Summary collapse

Instance Method Details

#add_error(record, attr_name, message) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/rere_validator.rb', line 26

def add_error(record, attr_name, message)
  message_options = {
    default: [DEFAULT_MESSAGE[message], options[:message]],
    scope: [:errors, :messages]
  }
  record.errors.add(attr_name, I18n.t(message, message_options))
end

#reserved?(value) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
37
# File 'lib/rere_validator.rb', line 34

def reserved?(value)
  add_reserved_words = @options[:add_reserved_words] || []
  (RESERVED_WORDS + add_reserved_words).include?(value.downcase)
end

#validate_each(record, attribute, value) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/rere_validator.rb', line 12

def validate_each(record, attribute, value)
  if reserved?(value)
    add_error(record, attribute, :reserved_words)
  end

  if value !~ /\A[a-zA-Z0-9_.-]+\z/
    add_error(record, attribute, :invalid_characters)
  elsif value.match(/\A[_.-].*\z/)
    add_error(record, attribute, :invalid_characters_at_begin)
  elsif value.match(/\A.*[_.-]\z/)
    add_error(record, attribute, :invalid_characters_at_end)
  end
end