【问题标题】:How to validate urls duplicated again and again如何验证一次又一次重复的网址
【发布时间】:2014-05-03 18:03:26
【问题描述】:

我想在 Rails 4 模型中验证 url。大多数事情都在工作,只是我被困在如何验证像

这样的 url
http://stackoverflow.com/questions/4716513http://stackoverflow.com/questions/4716513http://stackoverflow.com/questions/4716513

它的同一个 url 一次又一次地重复,目前我正在使用 ruby​​ URI lib 将给定的字符串解析为 url

【问题讨论】:

  • 您的示例是您认为有效的还是无效的(我相信它在技术上作为 URL 是有效的,或者至少被典型的浏览器和网站接受)?您目前如何验证 URL 字符串(请显示代码)?
  • 我正在尝试制作一个 url 缩短器,它可以接受巨大的 url 并将其缩短。这种情况是如果用户在表单字段中一次又一次地粘贴相同的网址
  • 在这种情况下,我不会修改用户输入。如果用户确实像你说的那样,让他去做。只需检查您的代码是否不会中断。
  • 谷歌不打扰:goo.gl/VI3lVp
  • 纠正用户的错误不是你的工作。

标签: ruby regex ruby-on-rails-4


【解决方案1】:
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)

【讨论】:

    猜你喜欢
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多