如何为Ruby的MIME::Types现有类型添加扩展名

3

MIME::Types 可以将 txt 识别为 text/plain

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

我希望它默认也可以为标签执行相同的操作,但是现在它还不能。
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个回答

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系统上):
orig_stdout = $stdout
$stdout = File.new('/dev/null', 'w')
# insert the code block from above
$stdout = orig_stdout

这个很完美,但是不确定为什么要将它转换为哈希表...这个也可以: text_plain = MIME::Types['text/plain'].first text_plain.extensions << 'tab' MIME::Types.add(text_plain) - iwiznia
@iwiznia,在我写这个问题的时候,那是不可能的(请参见 https://github.com/halostatue/mime-types/blob/master/History.rdoc 中的历史记录--您可以看到直到2013-10-27才引入了无哈希方法,几乎是在我写这篇文章两年后)。但哈希方法适用于旧版和新版,因此我将我的答案保持原样以获得最高兼容性。谢谢你的留言。 - Ben Lee

1
另一种方法是创建一个新的内容类型,例如: 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))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接