From e7be1ef1fabe7176921c283c7314234a0deb9efe Mon Sep 17 00:00:00 2001 From: neimad971 Date: Sat, 29 Dec 2018 23:41:52 +0100 Subject: [PATCH] updates code school url when protocol is missing tries with https first if possible then http --- app/models/code_school.rb | 19 +++++++++++++++++++ test/models/code_schools_test.rb | 22 ++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/app/models/code_school.rb b/app/models/code_school.rb index 9ffdff5e..e09afc0d 100644 --- a/app/models/code_school.rb +++ b/app/models/code_school.rb @@ -2,4 +2,23 @@ class CodeSchool < ApplicationRecord validates :name, :url, :logo, presence: true validates_inclusion_of :full_time, :hardware_included, :has_online, :online_only, :in => [true, false] has_many :locations, -> { order('state ASC, city ASC') }, dependent: :destroy + + before_create :check_scheme + + private + + def check_scheme + uri = URI.parse(url) + update_url(uri) if uri.scheme.nil? + end + + def update_url(uri) + candidate = 'https://' << uri.to_s + begin + HTTParty.get(candidate, timeout: 2) + rescue StandardError + candidate.sub!('s', '') + end + self.url = candidate + end end diff --git a/test/models/code_schools_test.rb b/test/models/code_schools_test.rb index e7a9e7f0..021eea67 100644 --- a/test/models/code_schools_test.rb +++ b/test/models/code_schools_test.rb @@ -16,4 +16,26 @@ def setup test 'rep_email should be present' do assert @code_school.rep_email.present? end + + test 'url should be present' do + assert @code_school.url.present? + end + + test 'url does not change when url is correct' do + previous_url = @code_school.url + @code_school.run_callbacks :create + assert @code_school.url.eql?(previous_url) + end + + test 'url gets updated with HTTPS scheme when url has no scheme' do + @code_school.url = 'stackoverflow.com' + @code_school.run_callbacks :create + assert @code_school.url.eql?('https://stackoverflow.com') + end + + test 'url gets updated with HTTP scheme when url has no scheme' do + @code_school.url = 'neverssl.com' + @code_school.run_callbacks :create + assert @code_school.url.eql?('http://neverssl.com') + end end