Sha256: 274780c8d2255cfa25acfd7a8b1f91f60ae247ebedce40ebab275112e3191425

Contents?: true

Size: 1.16 KB

Versions: 4

Compression:

Stored size: 1.16 KB

Contents

class CoordinateValidator < ActiveModel::EachValidator

  def validate_each(record, attribute, value)
    boundary = options.fetch(:boundary, :coordinate).to_sym
    unless BOUNDARIES.include?(boundary)
      raise ArgumentError,
        "Unknown boundary: #{boundary.inspect}. Valid boundaries are: #{BOUNDARIES.map(&:inspect).join(', '.freeze)}"
    end

    unless valid?(value, options)
      record.errors[attribute] << (options.fetch(:message, false) || I18n.t("active_validation.errors.messages.coordinate.#{boundary}"))
    end
  end

  private

  BOUNDARIES = [:coordinate, :latitude, :longitude].freeze

  def valid_length?(value)
    value.present?
  end

  def valid_latitude?(value)
    value >= -90 && value <= 90
  end

  def valid_longitude?(value)
    value >= -180 && value <= 180
  end

  def valid_boundary?(value, options)
    case options.fetch(:boundary, :coordinate).to_sym
    when :latitude
      valid_latitude?(value)
    when :longitude
      valid_longitude?(value)
    else
      valid_latitude?(value.first) && valid_longitude?(value.last)
    end
  end

  def valid?(value, options)
    valid_length?(value) &&
    valid_boundary?(value, options)
  end

end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
active_validation-2.6.0 lib/active_validation/validators/coordinate_validator.rb
active_validation-2.5.0 lib/active_validation/validators/coordinate_validator.rb
active_validation-2.4.0 lib/active_validation/validators/coordinate_validator.rb
active_validation-2.3.0 lib/active_validation/validators/coordinate_validator.rb