2

我正在使用 Ruby on Rails 3.2.9。我的模型类有一个link属性,在将相关对象存储到数据库之前,我想在该值(URL、字符串类型)不存在的情况下使用默认协议示例协议可以是http://https://ftp://ftps://依此类推;默认值为http://)。为了做到这一点,我正在考虑使用一些正则表达式实现 Rails 回调,也许可以使用URI Ruby library,但我在如何实现它方面遇到了麻烦。

任何想法?我怎么能/应该做到这一点?

4

2 回答 2

1

仅使用简单的正则表达式替换怎么样?

class String
  def ensure_protocol
    sub(%r[\A(?!http://)(?!https://)(?!ftp://)(?!ftps://)], "http://")
  end
end

"http://foo".ensure_protocol # => "http://foo"
"https://foo".ensure_protocol # => "https://foo"
"ftp://foo".ensure_protocol # => "ftp://foo"
"ftps://foo".ensure_protocol # => "ftps://foo"
"foo".ensure_protocol # => "http://foo"
于 2012-12-26T15:52:56.397 回答
0

before_validation 回调可能是您想要开始的地方

class YourModel < ActiveRecord::Base

  PROTOCOLS = ["http://", "https://", "ftp://", "ftps://"]
  validates_format_of :website, :with => URI::regexp(%w(http https ftp ftps))
  before_validation :ensure_link_protocol

  def ensure_link_protocol
    valid_protocols = ["http://", "https://", "ftp://", "ftps://"]
    return if link.blank?
    self.link = "http://#{link}" unless PROTOCOLS.any?{|p| link.start_with? p}
  end

end
于 2012-12-26T16:03:16.037 回答