Du3
Du3

Reputation: 1422

Cleanest way to inject into string

We are looking to optimize images with a thumbnail version, which are stored under a funky version of the existing URL:

I was going to look from the end of the string for the last '/' and replacing it with '/thumbnails/medium_'. In my case this always safe, but I can't figure out this kind of mutation in Ruby on Rails.

s = "https://image.s3-us-west-2.amazonaws.com/8/flower.jpg"
img_url = s.split('/')[-1] // should give 'flower.jpg'

The issue is to get everything before the last '/' to inject in 'thumbnails/medium_'. Any ideas?

Upvotes: 1

Views: 108

Answers (5)

Brad Werth
Brad Werth

Reputation: 17647

s = "https://image.s3-us-west-2.amazonaws.com/8/flower.jpg"
img_url = s.insert(s.rindex('/')+1, 'thumbnails/medium_')

# The above approach modifies the original string, if this is unsatisfactory, use:    
img_url = s.dup.insert(s.rindex('/')+1, 'thumbnails/medium_')

Upvotes: 4

spickermann
spickermann

Reputation: 106872

I would probably use URI and Pathname to work with URLs and file paths:

require 'uri'
require 'pathname'

url = "https://image.s3-us-west-2.amazonaws.com/8/flower.jpg"

uri  = URI.new(url)
path = Pathname.new(uri.path)
uri.path = "#{path.dirname}/thumbnails/medium_#{path.basename}"

uri.to_s
#=> "https://image.s3-us-west-2.amazonaws.com/8/thumbnails/medium_flower.jpg"

Upvotes: 2

sawa
sawa

Reputation: 168101

s = "https://image.s3-us-west-2.amazonaws.com/8/flower.jpg"
img_url = "#{File.dirname(s)}/thumbnails/medium_#{File.basename(s)}"
# => "https://image.s3-us-west-2.amazonaws.com/8/thumbnails/medium_flower.jpg"

Upvotes: 3

Aetherus
Aetherus

Reputation: 8888

s = "https://image.s3-us-west-2.amazonaws.com/8/flower.jpg"
s.sub /([^\/]+)$/, 'thumbnails/medium_\1'

The s.sub's 2nd argument should be quoted with single quotation mark, or you have to escape the backslash in the \1 part.

UPDATE

s.sub /([^\/]+?)(?=$|\?|#)$/, 'thumbnails/medium_\1'

In case there's a query string or a fragment or both, behind the path, which contains slashes.

Upvotes: 1

EugZol
EugZol

Reputation: 6545

It's #[Range] method what you need:

# a little performance optimization - no need to split split string twice
parts = s.split('/')
img_url = parts[0..-2].join('/') + "/thumbnails/medium_" + parts[-1]

On a side note. If you are using some Rails plugin for handling images (CarrierWave or Paperclip), you should use built-in mechanisms for URL interpolation.

Upvotes: 0

Related Questions