Class: ActiveModel::Validations::TwitterValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/active_validators/active_model/validations/twitter_validator.rb

Constant Summary collapse

TWITTER_USERNAME_REGEXP =

Basic username regexp

/([A-Za-z0-9_]{1,15})/i
TWITTER_URL_REGEXP =

Regexp used to detect twitter username within the URL.

%r{\Ahttps?://(?:www\.)?twitter.com/#{TWITTER_USERNAME_REGEXP}\z}i
TWITTER_ATSIGN_REGEXP =

Regexp to test using twitter username as @sign.

/\A@#{TWITTER_USERNAME_REGEXP}\z/i
TWITTER_NOATSIGN_REGEXP =

Regexp to test against usernames without the @sign

/\A#{TWITTER_USERNAME_REGEXP}\z/i

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/active_validators/active_model/validations/twitter_validator.rb', line 18

def validate_each(record, attribute, value)
  format = options[:format].to_sym if options[:format]

  if value.nil?
    record.errors.add(attribute, :blank)
  elsif format == :url
    match = value.match(TWITTER_URL_REGEXP)
    record.errors.add(attribute) unless match && !match[1].nil?
  elsif format == :username_with_at
    record.errors.add(attribute) unless value =~ TWITTER_ATSIGN_REGEXP
  else
    record.errors.add(attribute) unless value =~ TWITTER_NOATSIGN_REGEXP
  end
end