开发者

How to add to the extensions for an existing type in Ruby's MIME::Types

开发者 https://www.devze.com 2023-04-06 12:45 出处:网络
MIME::Types recognises 开发者_Python百科txt as text/plain require \'mime/types\' MIME::Types.type_for(\"txt\").first.to_s# => \"text/plain\"

MIME::Types recognises 开发者_Python百科txt as text/plain

require 'mime/types'
MIME::Types.type_for("txt").first.to_s  # => "text/plain"

I want it to do the same thing for tab, which it doesn't by default

MIME::Types.type_for("tab").first.to_s  # => ""

So given that:

MIME::Types['text/plain'].first.extensions

is ["txt", "asc", "c", "cc", "h", "hh", "cpp", "hpp", "dat", "hlp"], why doesn't the following work:

MIME::Types['text/plain'].first.extensions.push("tab")
MIME::Types.type_for("tab").first.to_s  # => still just ""


Mime::Type doesn't appear to have any methods for adding extensions to an existing registered handler. What you can do is convert an existing handler to a hash, add in your own extension, then re-register the handler. This will output a warning, but it will work:

text_plain = MIME::Types['text/plain'].first.to_hash
text_plain['Extensions'].push('tab')
MIME::Types.add(MIME::Type.from_hash(text_plain))
MIME::Types.type_for("tab").first.to_s # => 'text/plain'

Or if you want to be clever and confusing and do it all in one line:

MIME::Types.add(MIME::Type.from_hash(MIME::Types['text/plain'].first.to_hash.tap{ |text_plain| text_plain['Extensions'].push('tab') }))
MIME::Types.type_for("tab").first.to_s # => 'text/plain'

If for some reason you need to suppress the warning message, you can do it like this (assuming you are running the code on a linux-y system):

orig_stdout = $stdout
$stdout = File.new('/dev/null', 'w')
# insert the code block from above
$stdout = orig_stdout


another way is to creating a new content type, e.g

stl_mime_type_hash = MIME::Type.new('application/vnd.ms-pkistl').to_hash stl_mime_type_hash['Extensions'].push('stl') MIME::Types.add(MIME::Type.from_hash(stl_mime_type_hash))

0

精彩评论

暂无评论...
验证码 换一张
取 消