Ruby - How to set derivatives filename with Shrine from data_uri (base64)

416 views Asked by At

Following from this question: Ruby - How to set data_uri (base64) filename with Shrine

This works perfectly for my use case, however, the derivatives that are created all have the filename "image_processing_xxx". The URLs look great, but when you right-click to download each image the filename doesn't look right or match the URL.

Is it possible to rename these to match the new original filename - and include a custom "_2x" or "_mobile" at the end of each (before .png/.jpeg)? Can I override it in somewhere? I've tried a lot of plugins but so far am having no such luck.

1

There are 1 answers

0
Kobius On BEST ANSWER

If anyone is trying to do the same, I've tested this working method:

add_metadata :filename do |io, record: nil, derivative: nil, **context|

  # Get file extension
  mime_type = context[:metadata]['mime_type']
  extension = Shrine.infer_extension(mime_type)

  # Set filename
  if derivative
    "#{derivative.to_s.dasherize}-photo-#{record.slug}" + extension.to_s
  else
    "original-photo-#{record.slug}" + extension.to_s
  end

end

This gives derivatives named download URLs, and "original" for the original file, both with the correct file extension.