返回顶部

收藏

正则表达式 Ruby中创建URL排列

更多
# return 4 urls, with and without trailing slash, with and without www
# useful for matching urls passed as params into some function,
# "does this url exist?"... need to make sure you check permutations
def url_permutations(url)
  url, params = url.split("?")
  # without_trailing_slash, with www
  a = url.gsub(/\/$/, "").gsub(/http(s)?:\/\/([^\/]+)/) do |match|
    protocol = "http#{$1.to_s}"
    domain = $2
    domain = "www.#{domain}" if domain.split(".").length < 3 # www.google.com == 3, google.com == 2
    "#{protocol}://#{domain}"
  end
  # with_trailing_slash, with www
  b = "#{a}/"
  # without_trailing_slash, without www
  c = a.gsub(/http(s)?:\/\/www\./, "http#{$1.to_s}://")
  # with_trailing_slash, without www
  d = "#{c}/"

  [a, b, c, d].map { |url| "#{url}?#{params}"}
end

]

标签:ruby

收藏

0人收藏

支持

0

反对

0

相关聚客文章
  1. 博主 发表 2009-04-06 16:00:00 使用SVN+SSH同步Ruby On Rails代码的脚本
  2. 博主 发表 2014-01-08 14:38:53 Ruby on Rails 中使用 Markdown 语法,及代码高亮
  3. 博主 发表 2014-01-13 10:23:02 用 Nginx 和 Unicorn 部署 Ruby on Rails 应用
  4. 博主 发表 2018-06-19 00:26:00 ruby/rails - 根据浏览器的语言,来自动识别
  5. Alex Wood 发表 2014-10-15 13:06:29 Deploying Ruby on Rails Applications to AWS OpsWor
  6. Alex Wood 发表 2014-10-22 12:04:19 Caching the Rails Asset Pipeline with Amazon Cloud
  7. Trevor Rowe 发表 2014-11-18 19:04:17 Using Resources
  8. Trevor Rowe 发表 2014-11-20 19:04:22 Waiters
  9. Trevor Rowe 发表 2014-11-20 19:04:22 Waiters
  10. Trevor Rowe 发表 2014-11-26 19:04:20 Client Response Stubs
  11. Alex Wood 发表 2014-12-02 17:32:13 AWS re:Invent 2014 Ruby Recap
  12. Alex Wood 发表 2014-12-10 17:20:18 Using Amazon RDS with Ruby on Rails and AWS OpsWor

发表评论