2012-03-03 43 views
12

我正在使用Thor并尝试将YAML输出到文件。在irb我得到了我的期望。 YAML格式的纯文本。但是,当Thor的一部分方法,其输出是不同的...Thor&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 

任何想法?

+1

我只是跑你的例子,它给了我完全没有输出。我跑了0.14.6。 – Maran 2012-03-03 23:14:11

+0

感谢您花时间检查。在这一点上我不知道该怎么做。我使用Ruby 1.9.3p125,如果这样做有什么不同的话。 :) – cp3 2012-03-04 02:00:42

+1

我安装了1.9。3并再次运行,实际上是二进制输出。我注意到YAML在安装过程中得到了升级。这可能与该升级版本有关。 – Maran 2012-03-04 08:05:18

回答

14

所有Ruby 1.9字符串都附有一个编码。

YAML将一些非UTF8字符串编码为二进制,即使它们看起来无辜,没有任何高位字符。你可能会认为你的代码总是使用UTF8,但是builtins可以返回非UTF8字符串(例如File path例程)。

要避免二进制编码,请在调用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" 
7

的例子后的版本1.9.3p125,红宝石内置的YAML引擎将以不同于以前的方式对待所有BINARY编码。你所需要做的就是在你的String.to_yaml之前设置正确的非二进制编码。

在红宝石1.9,所有字符串对象附加一个编码对象 和如以下博客(由James爱德华格雷II)提到的,红宝石已经建立在三个类型的编码时,产生字符串: http://blog.grayproductions.net/articles/ruby_19s_three_default_encodings

一个编码的可能解决问题=>源代码编码

这是您的源代码的编码,并且可以通过在所述第一线路或第二线路添加魔编码串(如果有一个是指定SHA-爆炸串在你的源代码的第一行) 魔术编码代码可能是下列之一:

  • #编码:UTF-8
  • #编码:UTF-8
  • # - - 编码:UTF-8 - -

所以你的情况,如果你使用Ruby 1.9.3p125或更高版本,这应该是在你的代码的开头加入魔术编码的一个解决。

# encoding: utf-8 
require 'thor' 
class Foo < Thor 
    include Thor::Actions 

    desc "bar", "test" 
    def bar 
    test = {"name" => "Xavier", "age" => 30} 
    puts test 
    #{"name"=>"Xavier", "age"=>30} 
    puts test["name"].encoding.name 
    #UTF-8 
    puts test.to_yaml 
    #--- 
    #name: Xavier 
    #age: 30 
    puts test.to_yaml.encoding.name 
    #UTF-8 
    end 
end 
0

我一直在使用1.9.3p545在Windows上苦苦挣扎 - 只是使用包含字符串的简单哈希函数 - 而没有Thor。

宝石ZAML解决了这个问题很简单:

require 'ZAML' 
yaml = ZAML.dump(some_hash) 
File.write(path_to_yaml_file, yaml)