简体   繁体   中英

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.

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. Any help would be appreciated.

Ruby has methods available to get you there easily:

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. 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.

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:

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.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. 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

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

String#match

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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