From a651f079d8f9dd2a7b131b7f7fab108a82a2a503 Mon Sep 17 00:00:00 2001 From: Brenda Wallace Date: Mon, 11 Nov 2019 17:41:46 +1300 Subject: [PATCH] Simplify garden.name validation regexp --- app/models/garden.rb | 25 ++++++++++++------------- spec/models/garden_spec.rb | 12 ++++++------ 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/app/models/garden.rb b/app/models/garden.rb index d763c02e5..1ab894986 100644 --- a/app/models/garden.rb +++ b/app/models/garden.rb @@ -22,23 +22,16 @@ class Garden < ApplicationRecord validates :location, length: { maximum: 255 } validates :slug, uniqueness: true + + before_validation :strip_blanks validates :name, uniqueness: { scope: :owner_id } - validates :name, - format: { - with: /\A((?!\\n)(?!\R)[\p{L}\p{M}\d\s[:ascii:](?!\\n)])*\z/ - }, - allow_nil: false, - allow_blank: false, - presence: true, - length: { maximum: 255 } - + format: { without: /\n/, message: "must contain no newlines" }, + allow_nil: false, allow_blank: false, presence: true, + length: { maximum: 255 } validates :area, - numericality: { - only_integer: false, - greater_than_or_equal_to: 0 - }, + numericality: {only_integer: false, greater_than_or_equal_to: 0 }, allow_nil: true AREA_UNITS_VALUES = { @@ -76,4 +69,10 @@ class Garden < ApplicationRecord p.save end end + + protected + + def strip_blanks + self.name = self.name.strip unless name.nil? + end end diff --git a/spec/models/garden_spec.rb b/spec/models/garden_spec.rb index ba25af967..c62fd0f1d 100644 --- a/spec/models/garden_spec.rb +++ b/spec/models/garden_spec.rb @@ -37,21 +37,21 @@ describe Garden do garden.should be_valid end + it "allows some punctuation" do + garden = FactoryBot.build(:garden, name: "best-garden-eva!") + garden.should be_valid + end + it "doesn't allow a name with only spaces" do garden = FactoryBot.build(:garden, name: " ") garden.should_not be_valid end - it "doesn't allow a new line chars in garden names" do + it "doesn't allow new line chars in garden names" do garden = FactoryBot.build(:garden, name: "My garden\nI am a 1337 hacker") garden.should_not be_valid end - it "doesn't allow a new lines in garden names" do - garden = FactoryBot.build(:garden, name: 'My garden\nI am a 1337 hacker') - garden.should_not be_valid - end - it "has an owner" do garden.owner.should be_an_instance_of Member end