【问题标题】:How to prepend URLs with a default protocol if it's absent?如果没有默认协议,如何在 URL 前添加默认协议?
【发布时间】:2012-12-12 03:21:19
【问题描述】:

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

有什么想法吗?我该怎么做?

【问题讨论】:

    标签: ruby-on-rails ruby regex ruby-on-rails-3 url


    【解决方案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"
    

    【讨论】:

      【解决方案2】:

      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
      

      【讨论】:

      • 由于您使用URI.regexp 来确定有效性,我建议您也使用该库来查找协议:self.link = "http://#{website}" if PROTOCOLS.include? URI.parse(link).scheme。那么 PROTOCOLS 应该是 w%{http https ftp ftps} 并且也可以在 :with =&gt; RI::regexp(PROTOCOLS) 中重复使用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多