Rails: how to get a file extension/postfix based o

2019-02-04 12:58发布

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.

2条回答
The star\"
2楼-- · 2019-02-04 13:27

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.

查看更多
手持菜刀,她持情操
3楼-- · 2019-02-04 13:33

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

Mime::Type.lookup('image/jpeg').symbol.to_s
# => "jpg"
查看更多
登录 后发表回答