From 25956c51414950bba96c21c4351c2426a86f3fdb Mon Sep 17 00:00:00 2001 From: Colin Darie Date: Fri, 21 Apr 2023 17:26:28 +0200 Subject: [PATCH] fix(geoarea): geometry must not be nil --- app/models/geo_area.rb | 2 +- app/validators/geo_json_validator.rb | 6 +++++- spec/factories/geo_area.rb | 1 + spec/models/geo_area_spec.rb | 10 ++++++++++ 4 files changed, 17 insertions(+), 2 deletions(-) diff --git a/app/models/geo_area.rb b/app/models/geo_area.rb index d18252301..9f691c39e 100644 --- a/app/models/geo_area.rb +++ b/app/models/geo_area.rb @@ -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 diff --git a/app/validators/geo_json_validator.rb b/app/validators/geo_json_validator.rb index e17bdfecb..085d0225e 100644 --- a/app/validators/geo_json_validator.rb +++ b/app/validators/geo_json_validator.rb @@ -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 diff --git a/spec/factories/geo_area.rb b/spec/factories/geo_area.rb index 45cdb2f30..457f88884 100644 --- a/spec/factories/geo_area.rb +++ b/spec/factories/geo_area.rb @@ -2,6 +2,7 @@ FactoryBot.define do factory :geo_area do association :champ properties { {} } + geometry { {} } trait :cadastre do source { GeoArea.sources.fetch(:cadastre) } diff --git a/spec/models/geo_area_spec.rb b/spec/models/geo_area_spec.rb index 0cd51a7c6..aa9f037f4 100644 --- a/spec/models/geo_area_spec.rb +++ b/spec/models/geo_area_spec.rb @@ -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