Is it possible to specify formatting options for to_yaml in ruby?

前端 未结 5 1176
说谎
说谎 2020-12-11 14:36

The code

require \'yaml\'
puts YAML.load(\"
is_something:
  values: [\'yes\', \'no\']
\").to_yaml

produces

--- 
is_somethin         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-11 15:26

    Just another hack to specify the output style, but this one allows to customize it per specific object, instead of globally (e.g. for all arrays).

    https://gist.github.com/jirutka/31b1a61162e41d5064fc

    Simple example:

    class Movie
      attr_accessor :genres, :actors
    
      # method called by psych to render YAML
      def encode_with(coder)
        # render array inline (flow style)
        coder['genres'] = StyledYAML.inline(genres) if genres
        # render in default style (block)
        coder['actors'] = actors if actors
      end
    end
    

提交回复
热议问题