3

According to Phrogz and my answers to this question, the yaml library used with Ruby 1.9 seems to only allow a few options: indentation, line_width, canonical, (and line_wrap by setting line_width to -1). I want to use the other options that the official YAML format allows, including but not limited to use_block. Is it possible to activate other options with a small hack, or is there an alternative yaml library for Ruby 1.9 that allows the other options? And why does the yaml library not provide the other options?

Community
  • 1
  • 1
sawa
  • 165,429
  • 45
  • 277
  • 381

1 Answers1

0

As a temporal solution, I found ya2yaml. This has some problems, though.

  1. It does not have the ability to read. It is only for writing.
  2. It does not fully output unpopular Ruby classes with !ruby/class ... notation. In yaml gem, this notation is fully used so that a Ruby class is preserved in a ruby-yaml-ruby round trip.
  3. It uses the !ruby/symbol ... notation for symbols, which looks lengthy compared to the :... notation used in yaml gem.
  4. It uses the ? ... \n: yaml syntax for a hash key, which looks lengthy compared to the more compact hash notation with yaml gem.

Problem 2 is not a big deal for me so far, so I am using the combination of yaml and ya2yaml gems in the following way to overcome problems 1, 3, 4:

require "yaml" # For reading.
require "ya2yaml" # For writing.

class Object
  def to_yaml # Method for writing in yaml
    ya2yaml.
    # Put hash key on a single line if it is a symbol
    gsub(/^(\s*)\? !ruby\/symbol (\S+)\s+/, '\1:\2').
    # Use symbol literal
    gsub(/(?<=\s)!ruby\/symbol /, ':')
  end
end
sawa
  • 165,429
  • 45
  • 277
  • 381