如何在Ruby的MIME :: Types中添加现有类型的扩展

时间:2011-09-19 21:28:10

标签: ruby mime-types

MIME::Typestxt视为text/plain

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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))