相关疑难解决方法(0)

如何解析URL并提取所需的子字符串

说我有这样的字符串: "http://something.example.com/directory/"

我想要做的是解析这个字符串,并"something"从字符串中提取.

第一步,显然要检查以确保字符串包含"http://"- 否则,它应该忽略该字符串.

但是,我如何才能"something"在该字符串中提取?假设所有将要评估的字符串将具有类似的结构(即我正在尝试提取URL的子域 - 如果正在检查的字符串确实是有效的URL - 其中有效的开头"http://").

谢谢.

PS我知道如何检查第一部分,即我可以简单地将字符串拆分,"http://"但这并不能解决完整的问题,因为这会产生"http://something.example.com/directory/".我只想要的是"something",没有别的.

ruby parsing

15
推荐指数
2
解决办法
2万
查看次数

我可以使Rails / WEBrick将/ etc / hosts中的条目识别为子域(而不是域)吗?

我正在尝试将本地子域用于Rails应用程序,因此我在/etc/hosts文件中添加了以下行:

# add 'test' subdomain for localhost
127.0.0.1 test.localhost
Run Code Online (Sandbox Code Playgroud)

现在,我可以将浏览器指向,test.localhost:3000并且可以访问我的Rails应用程序。

但是,Rails或WEBrick会将整个织补唐解释为域:

# logging in the controller
logger.debug("domain: '#{request.domain}', subdomain: '#{request.subdomain}'")

# output in the console
domain: 'test.localhost', subdomain: ''
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法可以将WEBrick Rails解释test为子域?

谢谢!

更新资料

我最终做了before_action一个解决方法。

def set_domain_and_subdomain
  @domain = request.domain
  @subdomain = request.subdomain

  # HACK: force /etc/hosts subdomains
  if Rails.env.development?
    if m = request.domain.match(/([^\.]+).localhost/)
      @subdomain = m[1]
      @domain = 'localhost'
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

但是我仍然很好奇,是否有一种方法可以在我的计算机上实现通用(即在`/ etc / hosts之类的东西中)

subdomain ruby-on-rails webrick

1
推荐指数
1
解决办法
748
查看次数

标签 统计

parsing ×1

ruby ×1

ruby-on-rails ×1

subdomain ×1

webrick ×1