雷神&YAML输出为二进制? [英] Thor & YAML outputting as binary?
问题描述
我正在使用 Thor 并尝试将 YAML 输出到文件.在 irb 中,我得到了我的期望.YAML 格式的纯文本.但是当 Thor 中某个方法的一部分时,它的输出就不同了……
I'm using Thor and trying to output YAML to a file. In irb I get what I expect. Plain text in YAML format. But when part of a method in Thor, its output is different...
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 字符串都附加了编码.
All Ruby 1.9 strings have an encoding attached to them.
YAML 将一些非 UTF8 字符串编码为二进制,即使它们看起来很无辜,也没有任何高位字符.您可能认为您的代码始终使用 UTF8,但内置函数可以返回非 UTF8 字符串(例如文件路径例程).
YAML encodes some non-UTF8 strings as binary, even when they look innocent, without any high-bit characters. You might think that your code is always using UTF8, but builtins can return non-UTF8 strings (ex File path routines).
为避免二进制编码,请在调用 to_yaml 之前确保所有字符串编码均为 UTF-8.使用 force_encoding("UTF-8") 方法更改编码.
To avoid binary encoding, make sure all your strings encodings are UTF-8 before calling to_yaml. Change the encoding with force_encoding("UTF-8") method.
例如,这就是我将选项哈希编码为 yaml 的方式:
For example, this is how I encode my options hash into 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 将简单字符串编码为二进制的示例
Here is an example of yaml encoding simple strings as binary
>> x = "test"
=> "test"
>> x.encoding
=> #<Encoding:UTF-8>
>> x.to_yaml
=> "--- test
...
"
>> x.force_encoding "ASCII-8BIT"
=> "test"
>> x.to_yaml
=> "--- !binary |-
dGVzdA==
"
这篇关于雷神&YAML输出为二进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!