From 02bc134c593ad9617ac8137bfc0fa6b9aa85c087 Mon Sep 17 00:00:00 2001 From: "fabricio.albarnaz" Date: Mon, 15 Oct 2018 17:51:33 -0300 Subject: [PATCH] Change befor save check to format validation --- app/models/enterprise.rb | 11 +++++------ spec/models/enterprise_spec.rb | 6 +++--- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/app/models/enterprise.rb b/app/models/enterprise.rb index 7d4650ad0e..4f62d9f2f1 100644 --- a/app/models/enterprise.rb +++ b/app/models/enterprise.rb @@ -80,7 +80,7 @@ class Enterprise < ActiveRecord::Base before_validation :set_unused_address_fields after_validation :geocode_address - before_save :check_instagram_pattern + validates :instagram, format: /\A@[a-zA-Z0-9._]{1,30}\z/, :allow_blank => true after_touch :touch_distributors after_create :set_default_contact @@ -332,6 +332,10 @@ class Enterprise < ActiveRecord::Base abn.present? end + def instagram=(value) + write_attribute(:instagram, value.try(:gsub, %r{\Ahttps?://(?:www.)?instagram.com/([a-zA-Z0-9._]{1,30})/?\z}, '@\1')) + end + protected def devise_mailer @@ -427,9 +431,4 @@ class Enterprise < ActiveRecord::Base where('enterprises.id != ?', self.id). each(&:touch) end - - def check_instagram_pattern - return if self.instagram.blank? || self.instagram.exclude?('instagram.com') - self.instagram = "@#{self.instagram.split('/').last}" - end end diff --git a/spec/models/enterprise_spec.rb b/spec/models/enterprise_spec.rb index 28ce82b103..fa4877ff3b 100644 --- a/spec/models/enterprise_spec.rb +++ b/spec/models/enterprise_spec.rb @@ -149,10 +149,10 @@ describe Enterprise do end context "prevent an wrong instagram link pattern" do - let!(:e) { create(:enterprise, instagram: 'www.instagram.com/my_user') } + let(:e) { build(:enterprise, instagram: 'instagram.com/my_user') } - it "expects the instagram attribute to be in the correct pattern" do - expect(e.instagram).to eq('@my_user') + it "expects the instagram attribute to not be valid" do + expect(e).to_not be_valid end end end