我正在使用 Thor 并尝试将 YAML 输出到文件中。在 irb 中我得到了我所期望的。 YAML 格式的纯文本。但是当作为雷神方法的一部分时,它的输出是不同的......
class Foo < Thor
include Thor::Actions
desc "bar", "test"
def set
test = {"name" => "Xavier", "age" => 30}
puts test
# {"name"=>"Xavier", "age"=>30}
puts test.to_yaml
# !binary "bmFtZQ==": !binary |-
# WGF2aWVy
# !binary "YWdl": 30
File.open("data/config.yml", "w") {|f| f.write(test.to_yaml) }
end
end
有任何想法吗?
所有 Ruby 1.9 字符串都附加了编码。
YAML 将一些非 UTF8 字符串编码为二进制,即使它们看起来很无辜,没有任何高位字符。您可能认为您的代码始终使用 UTF8,但内置函数可以返回非 UTF8 字符串(例如文件路径例程)。
为了避免二进制编码,请在调用 to_yaml 之前确保所有字符串编码都是 UTF-8。使用force_encoding("UTF-8")方法更改编码。
例如,这就是我将选项哈希编码到 yaml 中的方式:
options = {
:port => 26000,
:rackup => File.expand_path(File.join(File.dirname(__FILE__), "../sveg.rb"))
}
utf8_options = {}
options.each_pair { |k,v| utf8_options[k] = ((v.is_a? String) ? v.force_encoding("UTF-8") : v)}
puts utf8_options.to_yaml
这是 yaml 将简单字符串编码为二进制的示例
>> x = "test"
=> "test"
>> x.encoding
=> #<Encoding:UTF-8>
>> x.to_yaml
=> "--- test\n...\n"
>> x.force_encoding "ASCII-8BIT"
=> "test"
>> x.to_yaml
=> "--- !binary |-\n dGVzdA==\n"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)