cmw
cmw

Reputation: 956

Remove URL prefix in Ruby

I have an S3 URL like so:

https://bucket.s3.amazonaws.com/uploads/1c4248b2-4256-4af4-ac1b-0e1e3f7ec2c8/filename.jpg

What I'd like to do, is, using Ruby, remove the prefix https://bucket.s3.amazonaws.com/ leaving only uploads/1c4248b2-4256-4af4-ac1b-0e1e3f7ec2c8/filename.jpg.

I'm unsure whether using gsub and just replacing the prefix (hardcoded) with empty space is the right way to go – or, if there's a more efficient approach.

url.gsub('https://bucket.s3.amazonaws.com/', '')

Upvotes: 0

Views: 195

Answers (1)

Shadwell
Shadwell

Reputation: 34774

You can use URI from ruby's standard library:

irb> require 'uri'
=> true

irb> u = URI("https://bucket.s3.amazonaws.com/uploads/1c4248b2-4256-4af4-ac1b-0e1e3f7ec2c8/filename.jpg")
=> #<URI::HTTPS:0x000000020995f0 URL:https://bucket.s3.amazonaws.com/uploads/1c4248b2-4256-4af4-ac1b-0e1e3f7ec2c8/filename.jpg>

irb> u.path
=> "/uploads/1c4248b2-4256-4af4-ac1b-0e1e3f7ec2c8/filename.jpg"

Alternatively u.request_uri returns any parameters on the URI too.

Upvotes: 1

Related Questions