Ruby to_yaml utf8 string

How can I make the ruby ​​to_yaml method to store utf8 strings with original characters, but not an escape sequence?

+3
source share
4 answers

This is probably a very bad idea, since I am sure that YAML has reasons for encoding characters as it happens, but undoing it is not so difficult:

require 'yaml'
require 'yaml/encoding'

text = "Ça va bien?"

puts text.to_yaml(:Encoding => :Utf8) # => --- "\xC3\x87a va bien?"
puts YAML.unescape(YAML.dump(text)) # => --- "Ça va bien?"
+3
source
require 'yaml'
YAML::ENGINE.yamler='psych'
'Résumé'.to_yaml # => "--- Résumé\n...\n"

Ruby comes with two YAML engines: syck and psych. Syck is old and not supported, but by default it is 1.9.2, so you need to switch to the psyche. UTF-8 mental dumps in UTF-8.

+7
source

Ya2Yaml RubyForge.

+3

Ruby 1.9.3+ : YAML- - Psych, UTF-8 .

For Ruby 1.9.2 - you need to install the gem psychand require it before you need yaml:

irb(main):001:0> require 'yaml'
#=> true
irb(main):002:0> require 'psych'
#=> true
irb(main):003:0> YAML::ENGINE
#=> #<YAML::EngineManager:0x00000001a1f642 @yamler="syck">
irb(main):004:0> "ça va?".to_yaml
#=> "--- \"\\xC3\\xA7a va?\"\n"
irb(main):001:0> require 'psych' # gem install psych
#=> true
irb(main):002:0> require 'yaml'
#=> true
irb(main):003:0> YAML::ENGINE
#=> #<YAML::EngineManager:0x00000001a1f828 @yamler="psych">
irb(main):004:0> "ça va bien!".to_yaml
#=> "--- ça va bien!\n...\n"

Alternatively, install yamleras Eugene suggests (if you installed the stone psych):

irb(main):001:0> require 'yaml'
#=> true
irb(main):002:0> YAML::ENGINE.yamler
#=> "syck"
irb(main):003:0> "ça va?".to_yaml
#=> "--- \"\\xC3\\xA7a va?\"\n"
irb(main):004:0> YAML::ENGINE.yamler = 'psych'
#=> "psych"
irb(main):005:0> "ça va".to_yaml
#=> "--- ça va\n...\n"
+2
source

Source: https://habr.com/ru/post/1713129/


All Articles