简体   繁体   English

获取没有文件名的URL?

[英]Get URL without filename?

I'm trying to figure out how to parse a URL in Rails, and return everything except the filename, or, everything except that which follows the last backslash. 我试图弄清楚如何在Rails中解析URL,并返回除文件名以外的所有内容,或者返回除最后一个反斜杠之后的所有内容。

For example, I'd like: 例如,我想要:

http://bucket.s3.amazonaws.com/directoryname/1234/thumbnail.jpg

to become: 成为:

http://bucket.s3.amazonaws.com/directoryname/1234/

I've found every way to parse a URI, but this. 我已经找到了解析URI的所有方法,但这是可以的。 Any help would be appreciated. 任何帮助,将不胜感激。

Ruby has methods available to get you there easily: Ruby提供了一些可让您轻松到达那里的方法:

File.dirname(URL) # => "http://bucket.s3.amazonaws.com/directoryname/1234"

Think about what a URL/URI is: It's a designator for a protocol, a site, and a directory-path to a resource. 考虑一下URL / URI是什么:它是协议,站点和资源的目录路径的指示符。 The directory-path to a resource is the same as a "path/to/file", so File.dirname works nicely, without having to reinvent that particular wheel. 资源的目录路径与“路径/到/文件”相同,因此File.dirname可以很好地工作,而不必重新发明该特定的轮子。

The trailing / isn't included because it's a delimiter between the path segments. 尾部的/不包含在内,因为它是路径段之间的分隔符。 You generally don't need that, because joining a resource to a path will automatically supply it. 通常,您不需要这样做,因为将资源连接到路径会自动提供资源。

Really though, using Ruby's URI class is the proper way to mangle URIs: 确实,使用Ruby的URI类是处理URI的正确方法:

require 'uri'

URL = 'http://bucket.s3.amazonaws.com/directoryname/1234/thumbnail.jpg'
uri = URI.parse(URL)
uri.merge('foo.html').to_s 
# => "http://bucket.s3.amazonaws.com/directoryname/1234/foo.html"

URI allows you to mess with the path easily too: URI也使您可以轻松弄乱路径:

uri.merge('../foo.html').to_s 
# => "http://bucket.s3.amazonaws.com/directoryname/foo.html"

uri.merge('../bar/foo.html').to_s 
# => "http://bucket.s3.amazonaws.com/directoryname/bar/foo.html"

URI is well-tested, and designed for this purpose. URI经过了充分的测试,并为此目的而设计。 It will also allow you to add query parameters easily, encoding them as necessary. 它还将允许您轻松添加查询参数,并根据需要对其进行编码。

File name 文档名称

"http://bucket.s3.amazonaws.com/directoryname/1234/thumbnail.jpg".match(/(.*\/)+(.*$)/)[2]
=> "thumbnail.jpg"

URL without the file name 不带文件名的URL

"http://bucket.s3.amazonaws.com/directoryname/1234/thumbnail.jpg".match(/(.*\/)+(.*$)/)[1]
=> "http://bucket.s3.amazonaws.com/directoryname/1234/"

String#match 字串#match

'http://a.b.pl/a/b/c/d.jpg'.rpartition('/').first
=> "http://a.b.pl/a/b/c"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM