Class: UrlFormatValidator

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

Instance Method Summary collapse

Instance Method Details

#format_value(record, attribute, value) ⇒ Object



11
12
13
14
# File 'lib/url_format/url_format_validator.rb', line 11

def format_value(record, attribute, value)
  return value if value =~ /\Ahttps?:\/\//
  record.send("#{attribute}=","http://#{value}")
end

#url_regexpObject



18
19
20
# File 'lib/url_format/url_format_validator.rb', line 18

def url_regexp
  /\Ahttps?:\/\/([\A\s:@]+:[\A\s:@]*@)?[-[[:alnum:]]]+(\.[-[[:alnum:]]]+)+\.?(:\d{1,5})?([\/?]\S*)?\z/iux
end

#validate_each(record, attribute, value) ⇒ Object



2
3
4
5
6
7
8
9
# File 'lib/url_format/url_format_validator.rb', line 2

def validate_each(record, attribute, value)
  value = format_value(record, attribute, value)
  unless URI.parse(value).kind_of?(URI::HTTP) && value =~ url_regexp
    record.errors[attribute] << (options[:message] || "is invalid")
  end
rescue URI::InvalidURIError
  record.errors[attribute] << (options[:message] || "is invalid")
end