检查URL有效且属于特定域

时间:2015-06-16 21:48:18

标签: ruby-on-rails ruby

我使用rails构建应用。该应用程序将允许用户在表单中输入URL,然后保存到数据库。 (例如,链接到GitHub repo的URL)

我想在保存之前验证用户输入的网址,以确保:

1,它是有效的网址(http,https)

2,它实际上是来自此网址的(200)响应

3,输入的URL具有域GitHub.com(或确保URL实际上转到GitHub)

只有满足这些后才会保存到数据库中。

到目前为止,我有:

class Repository < ActiveRecord::Base

Validates :url, presence: true
Validates_format_of :url, with: URI::regexp(%w(http https))

End

我相信我有一点被覆盖,有人可以就第2点和第3点提出建议吗?

非常感谢

2 个答案:

答案 0 :(得分:0)

使用Net::HTTP模块。

uri = URI('http://example.com/some_path?query=string')

Net::HTTP.start(uri.host, uri.port) do |http|

  request = Net::HTTP::Get.new uri.request_uri

  response = http.request request # Net::HTTPResponse object

  case response
    when Net::HTTPSuccess then
      # 2xx code received (success)
      response
    when Net::HTTPRedirection then
      # 3xx code received (redirected)
      location = response['location']
      warn "redirected to #{location}"
      fetch(location, limit - 1)
    else
      response.value
  end

end

如果不清楚,您可以修改此示例代码并将其包含在custom validation方法中,并像这样调用该方法:

  validate :my_custom_validation(some_uri_string)

答案 1 :(得分:0)

我建议您使用ActiveModel::EachValidator

# app/each_validators/github_url_validator.rb
class GitHubUrlValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless valid_github_url?(value)
      record.errors.add(attribute, options[:message] || :github_url)
    end
  end

  private

  def valid_github_url?(value)
    # Check if value is valid github url here.
  end
end

class Repository < ActiveRecord::Base
  validates :url, :github_url => true
end