Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thor & YAML outputting as binary?

Tags:

ruby

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

Any ideas?

like image 455
cp3 Avatar asked Mar 03 '12 22:03

cp3


People also ask

Is Thor a god or demigod?

Thor (/θɔːr/; from Old Norse: Þórr [ˈθoːrː]) is a prominent god in Germanic paganism. In Norse mythology, he is a hammer-wielding god associated with lightning, thunder, storms, sacred groves and trees, strength, the protection of mankind, hallowing, and fertility.

What is Thor's real name?

Thor Odinson, usually simply Thor, is a fictional character appearing in American comic books published by Marvel Comics.

Is Thor on Disney plus?

The new Thor movie is finally available to stream on Disney+, joining the streaming service's roster of other popular Marvel movies and TV shows, including She-Hulk: Attorney at Law and Doctor Strange in the Multiverse of Madness.

How old is Thor now?

After Thor encounters the Guardians of the Galaxy in a pivotal moment, he begins explaining how many foes he's fought over the years. To help illustrate his point more clearly, he reveals that he is 1,500 years old.


1 Answers

All Ruby 1.9 strings have an encoding attached to them.

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

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

Here is an example of yaml encoding simple strings as binary

>> 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"
like image 188
Aleksandar Totic Avatar answered Oct 16 '22 00:10

Aleksandar Totic