Sha256: 0f6a615360551f10de5ec60c03ed944988076cfca3acc86fa30821405d6b4b9d

Contents?: true

Size: 1.12 KB

Versions: 1

Compression:

Stored size: 1.12 KB

Contents

class CoordinateValidator < ActiveModel::EachValidator

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

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

  private

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

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

  def valid_length?(value)
    value.present?
  end

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

  def valid_boundary?(value, options)
    case options.fetch(:boundary, :coordinate)
    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

1 entries across 1 versions & 1 rubygems

Version Path
active_validation-3.0.0 lib/active_validation/validators/coordinate_validator.rb