0

I want to validate urls in Rails 4 model . most of things are working, just I am stucked how to validate urls like

http://stackoverflow.com/questions/4716513http://stackoverflow.com/questions/4716513http://stackoverflow.com/questions/4716513

Its a same url duplicated again and again , currently I am using ruby URI lib to parse given string as url

Alok Yadav
  • 159
  • 1
  • 7
  • Is your example something you consider valid, or not valid (I believe it to be technically valid as a URL, or at least accepted by a typical browser and web site)? How are you currently validating URL strings (please show code)? – Neil Slater May 03 '14 at 18:15
  • I am trying to make a url shortener that accept huge url and short it . the case is what if a user paste same url again and again in form field – Alok Yadav May 03 '14 at 19:03
  • 2
    In this case, I wouldn't modify the user input. If the user does like you said, let him do. Just check that your code won't break. – Micka May 03 '14 at 19:06
  • 1
    Google doesn't bother: http://goo.gl/VI3lVp – Micka May 03 '14 at 19:07
  • It is not your job to fix the mistakes of your users. – Sverri M. Olsen May 03 '14 at 19:49

1 Answers1

0
require 'net/http'

class URI_shortener
def self.shorten (input)
checked_input = remove_duplicates(input)
begin
  url = URI.parse(checked_input)
  #shorten
rescue
  puts "Input was unfixable, I swear!"
end
end

private

def self.remove_duplicates(user_input)
normal_separator ='http://'
secure_separator = 'https://'
if(user_input.include?(normal_separator))
  array= user_input.split(normal_separator)
  @cleaned_input = normal_separator
else
  array =  user_input.split(secure_separator)
  @cleaned_input = secure_separator
end
return @cleaned_input+array[1]
end
end

input ="http://stackoverflow.com/questions/4716513http://stackoverflow.com/questions/4716513http://stackoverflow.com/questions/4716513"
p url = URI_shortener::shorten(input)
input = "https://google.com"
p url = URI_shortener::shorten(input)
Jamato
  • 170
  • 1
  • 2
  • 6