-
Notifications
You must be signed in to change notification settings - Fork 108
updates code school url when protocol is missing #468
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There are two bugs that I see:
The first issue can be resolved by using the Addressable gem: def check_scheme
if url !~ /\Ahttps?:\/\//
uri = Addressable::URI.heuristic_parse(url, scheme: 'https')
begin
HTTParty.get(uri.to_s, timeout: 2)
rescue # (no need for StandardError. that's the default)
uri.scheme = 'http'
end
self.url = uri.to_s
end
end It'd be great to use the standard library instead of a gem, but Addressable works around this unfortunate behavior of URI: uri = URI('foo.com')
uri.scheme = 'https'
uri.to_s # https:foo.com For the second issue, we can update the code to def check_scheme
uri = Addressable::URI.heuristic_parse(url, scheme: 'https')
begin
HTTParty.get(uri.to_s, timeout: 2)
rescue
if uri.scheme == 'https'
uri.scheme = 'http'
retry
else
errors.add :url, 'unable to verify URL'
return
end
end
self.url = uri.to_s
end But I'm new here, so I'm not sure if y'all want to show a validation error here or not. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I believe that HTTParty only raises exceptions if it isn't able to connect to the server. If it receives a 404, though, you'd have to check the response object. But that might not be something y'all are trying to protect against. |
||
end | ||
end |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Currently
check_scheme
reads the URL attribute, thenupdate_url
writes it.To make the URL handling code reusable the API might look something like this:
For now though, I'd probably keep it all in one method.