class Gravaty::Parsers::Default

This class is an implementation of the Parsable duck type that checks the default option. The only needed parameter is a valid default option.

Author

Marco Bresciani

rubocop:disable Style/AsciiComments

Copyright

Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Marco Bresciani

rubocop:enable Style/AsciiComments

License

GNU General Public License version 3

Public Instance Methods

parse(value = nil) click to toggle source

The parsable duck type interface to every parser usage.

# File lib/gravaty/parsers/default.rb, line 46
def parse(value = nil)
  unless value.nil? || value.empty?
    unless DEFAULT_OPTIONS.include? value
      valid = %w[http https].index { |scheme| valid?(value, scheme) }

      raise ArgumentError, I18n.t('error.uri', value: value) if valid.nil?
    end

    return "d=#{CGI.escape(value)}"
  end
  ''
end

Private Instance Methods

valid?(value, scheme) click to toggle source

———————— here starts the list of private methods

# File lib/gravaty/parsers/default.rb, line 63
def valid?(value, scheme)
  return false if value.nil?
  return false if value.empty?

  parser = URI::Parser.new
  an_uri = parser.extract(value.downcase, scheme)

  return false if an_uri.nil?
  return false if an_uri.empty?

  begin
    an_uri = parser.parse an_uri[0]

    # See URI validation rules at
    # http://en.gravatar.com/site/implement/images/#default-image

    # rule 2
    return false if (an_uri.scheme == 'http') &&
                    (an_uri.port != Net::HTTP.http_default_port)
    return false if (an_uri.scheme == 'https') &&
                    (an_uri.port != Net::HTTP.https_default_port)

    # rule 3
    allowed = IMAGES_FORMATS
              .index { |format| an_uri.path.end_with? format }
    return false if allowed.nil?

    # rule 4
    return false unless an_uri.query.nil?
  rescue StandardError
    return false
  end
  true
end