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