排除一些模式的Rails 3 URL验证

问题描述

| 可以将ѭ0use与正则表达式一起使用吗? 这样可以确保与这些特定模式匹配的URL不会被验证或插入db。 编写此代码的最佳方法是什么?     

解决方法

根据具体情况,我可以采用几种方法。 首先,如果我必须匹配某些模式然后排除其他模式,则可能会执行以下操作:
validates_format_of :url,:with => /swanky pattern/,:unless => :beavis

def beavis
  self.url.match(/beavis/)
end
或者,如果您只需要排除某些模式
validate :i_hate_beavis

def i_hate_beavis
  errors.add(:url,\'cannot be beavis\') if self.url.match(/beavis/)
end
资源:http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validate     ,我采用了Geoff的方法并实现了以下内容:
validate :url_is_acceptable

URL_BLACKLIST = [
  /http:\\/\\/www.some-website.com\\/.*/,/http:\\/\\/www.other-website.com\\/.*/
]

def url_is_acceptable
  URL_BLACKLIST.each do |blacklisted_url|
    if self.url =~ blacklisted_url
      errors.add(:not_acceptable,\"is not acceptable\")
      return
    end
  end
end