Skip to content

Commit

Permalink
Review changes
Browse files Browse the repository at this point in the history
  • Loading branch information
danieljames-dj committed Aug 25, 2024
1 parent e37d6e9 commit 984e82e
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 27 deletions.
33 changes: 6 additions & 27 deletions app/models/competition_tab.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
# frozen_string_literal: true

require 'net/http'
require 'uri'

class CompetitionTab < ApplicationRecord
belongs_to :competition

Expand Down Expand Up @@ -37,30 +34,12 @@ def slug
competition.tabs.where("display_order > ?", display_order).update_all("display_order = display_order - 1")
end

private def url_exists?(url, max_redirects = 5)
uri = URI(url)
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
request = Net::HTTP::Get.new(uri)
response = http.request(request)
if (300..399).cover?(response.code.to_i) && max_redirects > 0
location = response['location']
return url_exists?(location, max_redirects - 1)
else
return response.code == '200'
end
end
end

validate :verify_if_urls_are_valid, on: :update
private def verify_if_urls_are_valid
base_url = Rails.application.routes.url_helpers.competitions_url + '/'
content.scan(/\[(.*?)\]\((.*?)\)/) do |match|
hyperlink = match[1]
unless hyperlink.starts_with?('http') # Validation is to be done only for the relative hyperlinks.
url = base_url + hyperlink
unless url_exists?(url)
errors.add(:content, "URL #{url} does not exist.")
end
validate :verify_if_urls_are_full_urls, on: :update
private def verify_if_urls_are_full_urls
content.scan(/\[(.*?)\]\((.*?)\)/).any? do |match|
url = match[1]
unless url.starts_with?('http://', 'https://')
errors.add(:content, I18n.t('competition_tabs.not_full_url_error_message', url: url))
end
end
end
Expand Down
1 change: 1 addition & 0 deletions config/locales/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2080,6 +2080,7 @@ en:
tabs_introduction_text: "Here you can add and edit tabs which are shown on the competition info page."
edit:
edit_tab_title: "Edit %{tab_name} tab"
not_full_url_error_message: "You have a relative URL (%{url}) in the content. Please enter full URLs with prefix http:// or https://."
#context: Key used for results (rankings, records, etc.)
results:
#context: On the rankings page
Expand Down

0 comments on commit 984e82e

Please sign in to comment.