Class: MirroringHouse::Validations::ValidatesFormatOfURI::InstanceMethods::URIFormatValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/mirroring_house/validations/validates_format_of_uri.rb

Constant Summary collapse

MESSAGES =
{ :scheme => :invalid_scheme, :host_blank => :host_cannot_be_blank, :general_error => :unable_to_parse }.freeze
SCHEMES =
[ :http, :https ].freeze
ALLOW_BLANK_HOST =
false.freeze
RESERVED_OPTIONS =
[]

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ URIFormatValidator

Returns a new instance of URIFormatValidator.

Raises:

  • (ArgumentError)


20
21
22
23
24
25
# File 'lib/mirroring_house/validations/validates_format_of_uri.rb', line 20

def initialize(options)
  raise ArgumentError, ":schemes must be an Array of Symbols describing allowed schemes" unless options[:schemes].nil? || (options[:schemes].is_a?(Array) && options[:schemes].all?{|a| a.is_a?(Symbol)})
  options[:schemes] ||= SCHEMES
  options[:allow_blank_host] ||= ALLOW_BLANK_HOST
  super
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/mirroring_house/validations/validates_format_of_uri.rb', line 27

def validate_each(record, attribute, value)

  errors_options = options.except(*RESERVED_OPTIONS)

  begin

    uri = URI.parse(value)

    record.errors.add(attribute, MESSAGES[:host_blank], errors_options) if uri.host.blank? && !options[:allow_blank_host]
    record.errors.add(attribute, MESSAGES[:scheme_invalid], errors_options) unless options[:schemes].map{|scheme| scheme.to_s}.include?(uri.scheme)

  rescue URI::InvalidURIError => e

    record.errors.add(attribute, MESSAGES[:general_error], errors_options)

  end
end