2011-09-19 85 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))