Class: TweetValidator::TweetLengthValidator

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

Constant Summary collapse

TWEET_MAX_LENGTH =
140

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.dummy_http_urlObject



31
32
33
# File 'lib/tweet_validator/tweet_length_validator.rb', line 31

def self.dummy_http_url
  dummy_url("http://", TweetValidator.config.short_url_length)
end

.dummy_https_urlObject



35
36
37
# File 'lib/tweet_validator/tweet_length_validator.rb', line 35

def self.dummy_https_url
  dummy_url("https://", TweetValidator.config.short_url_length_https)
end

.dummy_url(prefix, max_length) ⇒ Object



39
40
41
# File 'lib/tweet_validator/tweet_length_validator.rb', line 39

def self.dummy_url(prefix, max_length)
  prefix + "x" * (max_length - prefix.length)
end

.sanitize(tweet) ⇒ Object



20
21
22
# File 'lib/tweet_validator/tweet_length_validator.rb', line 20

def self.sanitize(tweet)
  tweet.gsub(/%<.+?>/, "").gsub(/%{.+?}/, "")
end

.shorten_url_length(tweet) ⇒ Object



24
25
26
27
# File 'lib/tweet_validator/tweet_length_validator.rb', line 24

def self.shorten_url_length(tweet)
  shorten_tweet = tweet.gsub(URI.regexp("http"), dummy_http_url).gsub(URI.regexp("https"), dummy_https_url)
  shorten_tweet.length
end

.valid_tweet?(tweet) ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
15
16
17
18
# File 'lib/tweet_validator/tweet_length_validator.rb', line 12

def self.valid_tweet?(tweet)
  return false unless tweet
  return false if tweet.empty?
  return false unless shorten_url_length(sanitize(tweet)) <= TWEET_MAX_LENGTH

  true
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



8
9
10
# File 'lib/tweet_validator/tweet_length_validator.rb', line 8

def validate_each(record, attribute, value)
  record.errors.add(attribute, :invalid_tweet) unless TweetLengthValidator.valid_tweet?(value)
end