Reputation: 2099
I have a text form to get URL from users.
Controller:
def create
link = Link.new(set_url_params)
if link.save
redirect...
else
flash[:notice] = "error"
end
end
In my model I have a method to add http if a given link does not have it:
before_validation :clean_link
def clean_link
self.url = "http://#{url}" unless self.url =~ /^https?:\/\//
end
Now I'd like to valid the url responds (+ get the final link after redirections) and save it or show an error message:
validate :response?
def response?
begin
self.url = HTTParty.head(self.url).request.last_uri.to_s
rescue SocketError
false
end
end
Example with valid URL:
input: cvcka.cz
clean_link: http://cvcka.cz
respond? https://cvcka.cz
link.valid? True
Invalid URL:
input: dada
clean_link: http://dada
respond?: rescue exception and return false
link.valid? - it returns true instead of false.
Why link.valid? with a string "dada" is true instead of false?
Upvotes: 1
Views: 122
Reputation: 36860
You need to add an entry to the model's errors so that the model's valid?
state will be false.
def response?
begin
self.url = HTTParty.head(self.url).request.last_uri.to_s
rescue SocketError
errors.add(:url, "Not a responsive URL")
return false
end
end
Upvotes: 1