LorneCurrie
LorneCurrie

Reputation: 412

Rails: how to get a file extension/postfix based on the mime type

Question I have is, does Ruby on Rails have a function similar to:

file_content_type = MIME::Types.type_for(file).first.content_type

that will return the file extension or postfix for a specific mime type? So if I pass in 'image/jpeg' the function will return 'jpg'

Looking for a cleaner way to code than having to write a case statement that does the same job.

Upvotes: 23

Views: 7898

Answers (5)

Kevin
Kevin

Reputation: 244

Marcel has ordered lists of extensions by mime type:

Marcel::TYPES[mime_type][0][0]

Upvotes: 1

asayamakk
asayamakk

Reputation: 163

Marcel can be your options too. It is shipped with Rails (ActiveStorage gem).

https://github.com/rails/marcel

It has hash of MimeType tables into extensions.

You do not have to invert hashes yourself. It might be memory friendly.

Please be aware that its constant is private and may change in future versions.

https://github.com/rails/marcel/blob/main/lib/marcel/tables.rb#L1261

iirb(main):008:0> Marcel::TYPES["image/jpeg"]
=>
[["jpg", "jpeg", "jpe", "jif", "jfif", "jfi"],
 [],
 "Joint Photographic Experts Group"]

Upvotes: 1

sandre89
sandre89

Reputation: 5918

If you are using ActiveStorage, there's a convenience method already provided by Rails, so you don't need to lookup the mime type yourself. For instance, with a Post model that has an attached image:

class Post < ApplicationRecord

  has_one_attached :image

You can use:

post_instance.image.blob.filename.extension

Upvotes: 0

jrochkind
jrochkind

Reputation: 23347

A better more up to date answer, since I found this googling.

Mime::Type.lookup('image/jpeg').symbol.to_s
# => "jpg"

Upvotes: 7

Andrew Marshall
Andrew Marshall

Reputation: 97004

Rack::Mime has this ability (and Rack is a dependency of Rails):

require 'rack/mime'
Rack::Mime::MIME_TYPES.invert['image/jpeg']  #=> ".jpg"

You may wish to memoize the inverted hash if you’re going to do the lookup often, as it’s not an inexpensive operation.

Upvotes: 48

Related Questions