"-6ren">
gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 08:01:36 24 4
gpt4 key购买 nike

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

最佳答案

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

关于ruby - 如何在 Ruby 的 MIME::Types 中添加现有类型的扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7477517/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com