fix(geoarea): geometry must not be nil

This commit is contained in:
Colin Darie 2023-04-21 17:26:28 +02:00
parent 925ebef551
commit 25956c5141
No known key found for this signature in database
GPG key ID: 4FB865FDBCA4BCC4
4 changed files with 17 additions and 2 deletions

View file

@ -51,7 +51,7 @@ class GeoArea < ApplicationRecord
scope :selections_utilisateur, -> { where(source: sources.fetch(:selection_utilisateur)) }
scope :cadastres, -> { where(source: sources.fetch(:cadastre)) }
validates :geometry, geo_json: true, allow_blank: false
validates :geometry, geo_json: true, allow_nil: false
before_validation :normalize_geometry
def to_feature

View file

@ -1,9 +1,13 @@
class GeoJSONValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
if options[:allow_nil] == false && value.nil?
record.errors.add(attribute, :blank, message: options[:message] || "ne peut pas être vide")
end
begin
RGeo::GeoJSON.decode(value.to_json, geo_factory: RGeo::Geographic.simple_mercator_factory)
rescue RGeo::Error::InvalidGeometry
record.errors[attribute] << (options[:message] || "n'est pas un GeoJSON valide")
record.errors.add(attribute, :invalid_geometry, message: options[:message] || "n'est pas un GeoJSON valide")
end
end
end

View file

@ -2,6 +2,7 @@ FactoryBot.define do
factory :geo_area do
association :champ
properties { {} }
geometry { {} }
trait :cadastre do
source { GeoArea.sources.fetch(:cadastre) }

View file

@ -81,6 +81,16 @@ RSpec.describe GeoArea, type: :model do
let(:geo_area) { build(:geo_area, :invalid_right_hand_rule_polygon, champ: nil) }
it { expect(geo_area.errors).to have_key(:geometry) }
end
context "nil" do
let(:geo_area) { build(:geo_area, geometry: nil) }
it { expect(geo_area.errors).to have_key(:geometry) }
end
context "allow empty {}" do
let(:geo_area) { build(:geo_area, geometry: {}) }
it { expect(geo_area.errors).not_to have_key(:geometry) }
end
end
end