2011-09-19 84 views
3

MIME::Types承认txttext/plain如何添加到扩展现有类型在Ruby的MIME类型::

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

我想要它做同样的事情tab,默认情况下

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

所以考虑到:

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

["txt", "asc", "c", "cc", "h", "hh", "cpp", "hpp", "dat", "hlp"],为什么没有了以下工作:

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

回答

3

Mime::Type似乎并不具有添加扩展到现有注册的处理程序的任何方法。你可以做的是将现有的处理程序转换为散列,添加你自己的扩展,然后重新注册处理程序。这将输出一个警告,但它会工作:

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' 

或者,如果你想聪明,混乱,做这一切在同一行:

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' 

如果由于某种原因,你需要压制警告信息,你可以做这样的(假设你运行的是Linux-y坐标系上的代码):

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

非常感谢!那就是诀窍。 – sanichi

+0

这是完美的,但不知道为什么要将其转换为哈希... 也适用于以下形式: text_plain = MIME :: Types ['text/plain']首先 text_plain.extensions <<'tab' MIME :: Types.add(text_plain) – iwiznia

+0

@iwiznia,在我写这个问题时,这是不可能的(请参阅https://github.com/halostatue/mime-types/blob/master/History.rdoc中的历史记录 - - 你可以看到这个无散列方法直到2013-10-27才被引入,在我写这篇文章后将近2年)。但哈希方法在旧版本和新版本中都有效,所以我将答案保留为最高兼容性。谢谢你的提示。 –

0

另一种方式是创建一个新的内容类型,例如

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))